15

I have an array of objects:

[
 {
    "enabled": true,
    "deviceID": "eI2K-6iUvVw:APA"
},
{
    "enabled": true,
    "deviceID": "e_Fhn7sWzXE:APA"
},
{
    "enabled": true,
    "deviceID": "e65K-6RRvVw:APA"
}]

A POST request is coming in with the deviceID of eI2K-6iUvVw:APA, all i want to do is to iterate the array, find the deviceID and change the enabled value to false.

How's that possible in javascript?

2
  • This is not proper JS data structure to start with. Commented Jul 20, 2017 at 20:00
  • The answer here is perfect. The "already has answers" above is to a 9 year old question and the answers aren't as good as this one. Commented Mar 26, 2020 at 0:33

2 Answers 2

35

You can use Array#find.

let arr = [
  {
    "enabled": true,
    "deviceID": "eI2K-6iUvVw:APA",
  },
  {
    "enabled": true,
    "deviceID": "e_Fhn7sWzXE:APA",
  },
  {
    "enabled": true,
    "deviceID": "e65K-6RRvVw:APA",
  },
];

const id = 'eI2K-6iUvVw:APA';

arr.find(v => v.deviceID === id).enabled = false;

console.log(arr);

Sign up to request clarification or add additional context in comments.

2 Comments

Any Idea, how we can update multiple key values at once, Like I need to update the deviceID along enabled
@LalitMohan Store found object in a variable and then change multiple properties: const obj = arr.find(v => v.deviceID === id); obj.enabled = false; obj.deviceID = 'your ID';
0

You could use Array.reduce to copy the array with the new devices disabled:

const devices = [ /* ... */ ];

const newDevices = devices.reduce((ds, d) => {
  let newD = d;
  if (d.deviceID === 'eI2K-6iUvVw:APA') {
    newD = Object.assign({}, d, { enabled: false });
  }
  return ds.concat(newD);
}, []);

2 Comments

reduce is not really ideal for this type of operation since you're recreating the whole array with one property changed.
@James can you propose a better solution?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.