Updating the values in an array of objects in react js

Viewed 83

I am trying to merge two objects that I am getting from 2 different api calls(the example here is just a sample). How can I merge the UserId array of object and the userCredentials array together in the user state? I want the state to look like this user:[{id: 1, name"john", country="de"},{id: 2, name"micheal", country="us"}]

...
    import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      user: []
    };
  }
  componentDidMount() {
    //api call 1 receiving user Id and name
    const UserId = [{ id: 1, name: "john" }, { id: 2, name: "micheal" }];
    this.setState({ user: UserId });

    //api call 2 receiving userCredentials
    const userCredentials = [
      { id: 1, country: "de" },
      { id: 1, country: "us" }
    ];

    this.setState({
      user: { ...this.state.user, credentials: userCredentials }
    });
  }

  render() {
    console.log("values", this.state);
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
      </div>
    );
  }
}


...

my sample code is

https://codesandbox.io/s/fancy-water-5lzs1?file=/src/App.js:0-754

2 Answers

Basically you need to map thru 1 array and find if each object in the array exists in another array and use spread operator and return the merged object in map callback

Working demo

Use the code below:

    // option 1 - if you know the keys of the object
    let merged = UserId.map(u => {
      const user = userCredentials.find(uc => uc.id === u.id);
      if (user) u["country"] = user.country;
      return u;
    });

    // option 2 - generic merge
    let merged2 = UserId.map(u => {
      const user = userCredentials.find(uc => uc.id === u.id);
      if (user) return { ...u, ...user };
      return u;
    });

You could use 'array.concat([])' to merge two array objects together. See bellow example.

let UserId = [{ id: 1, name: "john" }, { id: 2, name: "micheal" }];
const userCredentials = [{ id: 1, country: "de" },{ id: 1, country: "us" }];

const newArray = UserId.concat(userCredentials);

Since you have defined UserId as a const you cannot change it. So you have to make it to let or var to modify the variable.

Related