Home > Enterprise >  Replacing property value in one object array if property matches from another array of objects
Replacing property value in one object array if property matches from another array of objects

Time:11-21

I have javascript object like this

var arr1 = [{name:'qqq'}, 
           {name:'www'}, 
           {name:'eee'},
           {name:'rrr'}]

var arr2 = [{value:'qqq',url:'123'}, 
           {value:'www',url:'456'}]

I need to replace objects in arr1 with url from arr2 with matching name and value.

So here is the result I want to get:

var arr1  = [{name:'123'}, 
           {name:'456'}, 
           {name:'eee'},
           {name:'rrr'}]

CodePudding user response:

So you need to loop through arr1 and filter arr2 by name value, if you will get result, then replace name value with url value:

  let replacedValues = arr1.map(o1 => {
    let fResult = arr2.filter(o2 => o2.value === o1.name)[0]
    if(fResult) {
      o1.name = fResult.url
    }
    return o1
  })

CodePudding user response:

You can use Array#forEach and Array#find as in the following demo:

const
    arr1 = [{name:'qqq'}, {name:'www'}, {name:'eee'}, {name:'rrr'}],
    arr2 = [{value:'qqq',url:'123'},{value:'www',url:'456'}];
    
    arr1.forEach(({name}, i) => {
        const url = arr2.find(({value}) => value === name)?.url || 'NF';
        arr1[i] = { name: url };
    });
    
console.log( arr1 );
//NF: NOT FOUND

  • Related