Search code examples
javascriptarraystypescriptcomparisonkey-value

Compare array with object key/value by specific value in javascript


I need to create a new object key/value. In it i need the values from the already existing key/value object and i need to add values that are only in the array.

The array:

[{ name: "Computer", name: "Car", name: "House", name: "Flower"}]

The object key/value:

{ computer: { title: 'Computer', color: 'Black' }, house: { title: 'House', color: 'Red' }}

So in this case the new object would need to be:

{ computer: { title: 'Computer', color: 'Black' }, car: { title: 'Car', color:'' }, house: { title: 'House', color: 'Red' }, flower: { title: 'Flower', color:'' } } 

What is the easiest way to achieve this? I was thinking to loop over the array compare the values between them and extract the repeating ones, but i'm not sure how to do that.


Solution

  • I've made the assumption that that first array was meant to be an array of individual objects each with a key of 'name' as in the arr array.

    const arr = [ {name: "Computer"}, {name: "Car"}, {name: "House"}, {name: "Flower"}];
    const objVal = { 
            computer: { title: 'Computer', color: 'Black' }, 
            house: { title: 'House', color: 'Red' }
            };
    const expected = { 
            computer: { title: 'Computer', color: 'Black' }, 
            car: { title: 'Car', color:'' }, 
            house: { title: 'House', color: 'Red' }, 
            flower: { title: 'Flower', color:'' } 
            } 
    
    let returnObj = {};
    
    arr.forEach((element) => {
        const name = element.name;
        if (objVal[name.toLowerCase()]) {
            returnObj[name.toLowerCase()] = objVal[name.toLowerCase()];
        } else {
          returnObj[name.toLowerCase()] = {
            title: name,
            color: ''
          }
        }
    });
    
    console.log(returnObj);