Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the JavaScript way of updating an array of objects from another array? [duplicate]

I have an object called probe. It has a property called sensors which is an array.

var probe = {
    sensors = [
        { id: 1, checked: false },
        { id: 2, checked: true },
        { id: 3, checked: false },
        ... //more sensors
    ],
    ... //other properties
}

I have separate array which has an updated list of sensors like below.

var updatedSensors = [
    { id: 1, checked: true },
    { id: 3, checked: true }
];

I want to update the sensors array in the probe object from the values in the updatedSensors. How would I do that?

This can be easily achieved by using a couple of for-loops. But for-loops are not the pretty way of iterating in JavaScript, so I was wondering how to do this the preferred way.

Edit:

The objects in the updatedSensors is a subset of objects in probe.sensors. In other words, updatedSensors does not have all the objects (ids) that are there in the probe.sensors, but probe.sensors has all the objects (ids) that are in the updatedSensors.

Thanks.

like image 644
Anusha Dharmasena Avatar asked Dec 20 '25 17:12

Anusha Dharmasena


1 Answers

Try this bit of code:

probe.sensors.map(function (sensor) {
     // Loop through updated sensors & match sensor.id so we can reassign val
     updatedSensors.map(function (f) {
           if (f.id == sensor.id) {
               sensor.checked = f.checked
           }
     })
     return sensor;
})
like image 200
James111 Avatar answered Dec 23 '25 05:12

James111