Find and replace value inside an array of objects javascript [duplicate]

孤者浪人 提交于 2020-01-12 03:54:04

问题


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?


回答1:


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);



回答2:


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);
}, []);


来源:https://stackoverflow.com/questions/45222724/find-and-replace-value-inside-an-array-of-objects-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!