3

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.

9
  • 1
    Are the ids unique? If so, I would translate one of the arrays to a hash of id->checked to save some looping Commented Oct 25, 2016 at 23:03
  • 1
    If this was sensors = { 1:false, 2:true, 3:false } you would just use Object.assign. Commented Oct 25, 2016 at 23:04
  • @4castle Yes, that would have worked, but sensor objs in the array has other properties too. id and checked are only two properties. Commented Oct 25, 2016 at 23:10
  • @CodingWithSpike yes, the keys are unique. I don't know what translating to a hash means, but will look it up. Commented Oct 25, 2016 at 23:12
  • Please check stackoverflow.com/a/39127782/1463841 (using lodash unionBy lodash.com/docs/4.16.4#unionBy) Commented Oct 25, 2016 at 23:16

1 Answer 1

1

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;
})
Sign up to request clarification or add additional context in comments.

5 Comments

Too slow. Can be better if you index by id. And you shouldn't use map.
True. I just whipped it up in my inspector @Oriol
Wouldn't this overwrite the sensor objs in probe.sensors with objs in updatedSensors? I don't want that. I just want to update the checked property of each obj in probe.sensors.
No. Now it will just update the sensor.checked field to the value in the updatedSensor object
Yes, now it will :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.