-1

I got an array with objects inside it, and these objects got elements inside them. How will I address one of these objects by one of the elements?

let randomARR = [];

let a = {"name": "John", "age": 20, "PlaceOfBirth": "Germany"};
let b = {"name": "Simon", "age": 20, "PlaceOfBirth": "France"}; 
let c = {"name": "Michael", "age": 20, "PlaceOfBirth": "USA"};

randomARR.push(a);
randomARR.push(b);
randomARR.push(c);

result:

[{"name": "John", "age": 20, "PlaceOfBirth": "Germany"}, {"name": "Simon", "age": 20, "PlaceOfBirth": "France"}, {"name": "Michael", "age": 20, "PlaceOfBirth": "USA"}]

Let's say I would like to remove object b (name: Simon) out of the array by addressing the object by it's element "name", and not the it's position at the array.

SahiBalata
  • 313
  • 2
  • 5
  • 13

2 Answers2

2

You can use Array.prototype.filter

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

It iterates over all the elements of the array and based on the boolean returns keeps/removes it from the resultant array. You can set it to the current array to overwrite it.

let objArr = [{"name": "John", "age": 20, "PlaceOfBirth": "Germany"}, {"name": "Simon", "age": 20, "PlaceOfBirth": "France"}, {"name": "Michael", "age": 20, "PlaceOfBirth": "USA"}]

let newObj = objArr.filter(obj => obj.name !== "Simon");

// objArr = objArr.filter(obj => obj.name !== "Simon"); to overwrite
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
0

randomARR = randomARR.filter(o => o.name != 'Simon') ;

This is I think the way to go.

muasif80
  • 5,586
  • 4
  • 32
  • 45