Home > Back-end >  Removing arrays (objects) from json object (nodejs/javascript)
Removing arrays (objects) from json object (nodejs/javascript)

Time:10-02

how I can delete 1 or more entries from A json obj? for example have this json:

[{
  name: '1'
},
{
  name: '2'
},
{
  name: '2'
}]

and I want to delete the json objects where name is '2', how I can do that?

another question, what exactly the differences between arrays and json objects?

CodePudding user response:

const a = [{name: '1'},
  {name: '2'},
  {name: '2'}];
  
const newA = a.filter(s => s.name != '2');
console.log(newA);

If instead you want to edit the existing array, you can do:

const a = [{name: '1'},
  {name: '2'},
  {name: '2'}];

const newA = [];
while (a.length) {
  const front = a.shift();
  (front.name != '2') && newA.unshift(front);
}
newA.forEach(e => a.unshift(e));
console.log(a);

CodePudding user response:

When handling JSON in JavaScript, JSON objects are considered valid JavaScript expressions. Deleting one or more entries in a JSON object array can be done using one of several Array methods such as shift, pop, splice, or filter.
For your example, you can use filter to select only objects which don't have name: '2' (filter selects objects which return true for the given condition):

const myJson = [{ name: "1" }, { name: "2" }, { name: "3" }];
console.log(myJson.filter((obj) => obj.name !== "2"));

  • Related