-3

I have an array of JSONs like this:

[
  {
    id: 1,
    name: 'John'
  },
  {
    id: 2,
    name: 'Jack'
  },
  {
    id: 3,
    name: 'Peter'
  }
]

I want to find an object via it's id and add a deleted: true to it.

I'm wondering whats the easiest way to do this.

Alireza A2F
  • 519
  • 4
  • 26

3 Answers3

2

You can use the below generic function which needs you to pass the array and id of the object you want to update .

var arr = [
  {
    id: 1,
    name: 'John'
  },
  {
    id: 2,
    name: 'Jack'
  },
  {
    id: 3,
    name: 'Peter'
  }
];

 function addProperty(data,id){
data.forEach(obj => {
  if(obj.id === id){
    obj['deleted'] = true;
  }
});
   return data;
 }

let id = 1;
console.log(addProperty(arr, id));
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
2

You can use Array.prototype.find this would be the easiest way to do it

let users = [
  {
    id: 1,
    name: 'John'
  },
  {
    id: 2,
    name: 'Jack'
  },
  {
    id: 3,
    name: 'Peter'
  }
];
let id = 3;
let foundUser = users.find(user => user.id === id);

console.log('Users before modification', users);
foundUser.deleted = true;
console.log('Users after modification', users);
2

Try this:

var array = [
    {
        id: 1,
        name: 'John'
    },
    {
        id: 2,
        name: 'Jack'
    },
    {
        id: 3,
        name: 'Peter'
    }
]

for (var item in array){
    if (array[item].id === 1){
        array[item].deleted = true;
        break;
    }
}
console.log(array)

What it does is loop through every item in the array. It then checks if the corresponding indexed item has the value we are looking for. If yes, it adds a true attribute called deleted and breaks out of the loop.

Helix
  • 162
  • 3
  • 14