问题
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