Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 512
Stathis Ntonas Avatar asked Jul 20 '17 18:07

Stathis Ntonas


People also ask

How do you replace values in an array of objects?

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.

How do you replace an object in an array with another 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.

How do you duplicate an array in JavaScript?

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.


1 Answers

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);
like image 173
kind user Avatar answered Oct 01 '22 01:10

kind user