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?
To change the value of an object in an array: Use the Array. map() method to iterate over the array. Check if each object is the one to be updated. Use the spread syntax to update the value of the matching object.
Another way to replace an item in an array is by using the JavaScript splice method. The splice function allows you to update an array's content by removing or replacing existing elements. As usual, if you want to replace an item, you will need its index.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With