Updating values inside an object as soon as other array changes in Javascript React

Viewed 64

I have data/json in react of the following form stored in useState as follows:

const [Data, setData] = useState([]);
  
{
  "trees":{
     "name":"a",
     "age":"9",
     "height":"10",
     "location":"park"
  },
  "cars":{
     "name":"b",
     "age":"3",
     "height":"10",
     "location":"park"
  },
  "bikes":{
     "name":"c",
     "age":"110",
     "height":"10",
     "location":"park"
  }
}

Using WebSockets, I am getting another array of objects related to this data as follows: "cars":

[{
         "name":"b",
         "age":"3",
         "height":"99",
         "location":"park"
      },
      {
         "name":"c",
         "age":"734",
         "height":"9",
         "location":"park"
      }]

As can be seen in the above array, the value age and height are different for some objects than the original data. Therefore, what I want to do is that I want to update these values for respective things in the original data upon receiving from WebSocket data. I can't figure out the javascript to do so since the original data is of key-value pair form and updated data is an array of objects and setData every time new data comes from WebSocket.

1 Answers

You could try something like this. We have local Data as object and Array of Objects from WebSocket.

const Data = {
  "trees":{
     "name":"a",
     "age":"9",
     "height":"10",
     "location":"park"
  },
  "cars":{
     "name":"b",
     "age":"3",
     "height":"10",
     "location":"park"
  },
  "bikes":{
     "name":"c",
     "age":"110",
     "height":"10",
     "location":"park"
  }
}

const array = [{
             "name":"b",
             "age":"3",
             "height":"99",
             "location":"park"
          },
          {
             "name":"c",
             "age":"734",
             "height":"9",
             "location":"park"
          }]

Get values and keys from our local object.

const values = Object.values(Data)
const keys = Object.keys(Data)

Loop through the array from web socket and values from above and compare it and update the state.

array.forEach((arr) => {
    values.forEach((obj, i) => {
        if(arr.name === obj.name){
            Data[keys[i]] = arr
        }
    })
})

console.log(Data)

You may need to use useEffect to run the above loop everything new data comes in through socket.

Output:

{
    bikes: {name: 'c', age: '734', height: '9', location: 'park'}
    cars: {name: 'b', age: '3', height: '99', location: 'park'}
    trees: {name: 'a', age: '9', height: '10', location: 'park'}
}
Related