zamf
zamf

Reputation: 35

Find element and replace it

I want to make a function (or use library) that will search the array of objects find specific one by its property and replace it with the other object. E.g.:

var a = {name: "Jane", age: 29}

var arr = [{name: "Chris", age: 20}, {name: "Jane", age: 45}] 

arr.find(person => { if (a.name === person.name) {person = a})

Is there such a function?

Edit: It would be nice if there is no matched object in array it would push it to an array that object

Upvotes: 0

Views: 77

Answers (4)

jvdh
jvdh

Reputation: 308

You could use the find() method, as such:

var jane = {name: "Jane", age: 29}

var persons = [
    {name: "Chris", age: 20}, 
    {name: "Jane", age: 45}
];

function findPerson(person) {
    return function(element, index, array) {
        if(person.name === element.name) {
            array[index] = person;
            return true;
        }
        return false;
    }
}

persons.find(findPerson(jane));

This would replace the matched person if found and else returns undefined. So you could check if undefined is returned and add the person afterwards.

Upvotes: 0

Hassan Imam
Hassan Imam

Reputation: 22574

Since you want to modify the original array, you can use array#forEach(), just iterate through the array and replace the object which matches your a object name.

var a = {name: "Jane", age: 29}
var arr = [{name: "Chris", age: 20}, {name: "Jane", age: 45}] 

arr.forEach((person,index) => { 
if (a.name === person.name)
  arr[index] = a;
})
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

geekonaut
geekonaut

Reputation: 5954

You are probably looking for a wrapper around splice.

Your example would look like this:

arr.forEach((elem, index) => {
  if (elem.name !== a.name) return
  arr.splice(index, 1, a)
})

Upvotes: 1

Adam Azad
Adam Azad

Reputation: 11297

I can only think of Array#map

var a = {name: "Jane", age: 29}

var arr = [{name: "Chris", age: 20}, {name: "Jane", age: 45}] 

arr = arr.map(function(o){

   // if names match, return new object
   // otherwise, return original object
   return o.name == a.name ? a : o;

});

console.log( arr );

Upvotes: 2

Related Questions