Search code examples
javascriptnode.jsarraysobjectjavascript-objects

read javascript object to match if an item exists from an array of objects


I have an javascript array of objects named as obj and another object as finalObj

const obj = [{ 'name': 'skip', low: 20, high: 10 },
{ 'name': 'jump', low: 5, high: 20},
{ 'name': 'tall', low: 3, high: 2},
{ 'name': 'wind', low: 5, high: 10},
{ 'name': 'hire', low: 7, high: 6 }]

const finalObj = {
'Shopping mall': {
   'names': ['skip', 'jump'],
   'low': 0,
   'high': 0
},
'Parking garage': {
  'names': ['hire'],
  'low': 0,
  'high': 0
},
'Falling Tower': {
  'names': ['tall', 'wind'],
  'low': 0, 
  'high': 0
}
}

Now, if obj array of object with item name matches with finalObj of names, then add low and high values into final Obj.

the final output should be something like this:

const finalObj = {
'Shopping mall': {
   'names': ['skip', 'jump'],
   'low': 25,
   'high': 30
},
'Parking garage': {
  'names': ['hire'],
  'low': 7,
  'high': 6
},
'Falling Tower': {
  'names': ['tall', 'wind'],
  'low': 8, 
  'high': 12
}
}

I tried to iterate over obj but no luck so far..

for (const o in obj) {
 for (const f in Object.entries(finalObj)) {
   if (f[1]['names'].indexOf(obj[o].name >= 0)) {
     console.log("matched name : " + obj[o].name)
   }
 }
}

Solution

  • Use obj.forEach() to loop through the array. Then loop through the values in finalObj with Object.values(finalObj).forEach().

    Then use includes() to test whether the name from obj is in names, and add to the low and high properties.

    const obj = [
      { 'name': 'skip', low: 20, high: 10 },
      { 'name': 'jump', low: 5, high: 20},
      { 'name': 'tall', low: 3, high: 2},
      { 'name': 'wind', low: 5, high: 10},
      { 'name': 'hire', low: 7, high: 6 }
    ]
    
    const finalObj = {
      'Shopping mall': {
         'names': ['skip', 'jump'],
         'low': 0,
         'high': 0
      },
      'Parking garage': {
        'names': ['hire'],
        'low': 0,
        'high': 0
      },
      'Falling Tower': {
        'names': ['tall', 'wind'],
        'low': 0, 
        'high': 0
      }
    }
    
    obj.forEach(o =>
      Object.values(finalObj).forEach(f => {
        if (f.names.includes(o.name)) {
          f.low += o.low;
          f.high += o.high;
        }
      }));
    
    console.log(finalObj);