Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading