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.

Anusha Dharmasena
  • 1,219
  • 14
  • 25
  • 1
    Are the `id`s unique? If so, I would translate one of the arrays to a hash of `id`->`checked` to save some looping – CodingWithSpike Oct 25 '16 at 23:03
  • 1
    If this was `sensors = { 1:false, 2:true, 3:false }` you would just use [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). – 4castle Oct 25 '16 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. – Anusha Dharmasena Oct 25 '16 at 23:10
  • @CodingWithSpike yes, the keys are unique. I don't know what translating to a hash means, but will look it up. – Anusha Dharmasena Oct 25 '16 at 23:12
  • Please check http://stackoverflow.com/a/39127782/1463841 (using lodash `unionBy` https://lodash.com/docs/4.16.4#unionBy) – Andrea Puddu Oct 25 '16 at 23:16
  • @Oriol please can you link to the answer in the above comment? thanks – Andrea Puddu Oct 25 '16 at 23:23
  • @AndreaPuddu Where do you want me to put that link? – Oriol Oct 26 '16 at 00:28
  • @Oriol you marked this question as duplicate, but the link is referencing to another answer... so I guess you can change that? – Andrea Puddu Oct 26 '16 at 07:45
  • @AndreaPuddu It's only possible to close as a duplicate of another question, not as duplicate of another answer. And once I voted I can't add more duplicate questions targets, I only have one vote. – Oriol Oct 26 '16 at 11:38

1 Answers1

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;
})
James111
  • 15,378
  • 15
  • 78
  • 121