Search code examples
javascriptarraystypescriptjavascript-objects

Compare object properties by keys in javascript


I'm trying to make a comparison of the object properties by key. There are some sample data:

const data = [{
    "name": "John",
    "value": "30"
}, {
    "name": "Cindy",
    "value": "50"
}, {
    "name": "Mathew",
    "value": "80"
}, {
    "name": "Mike",
    "value": "35"
}];

so I would like to compare property values(value) of John and Mike names(key). If value of Mike is different than John than mutate value of Mike with value of John. There is some algorithm

data.map(obj => {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      let johnValue;
      let mikeValue;

      if(obj[key] == 'John') {
        johnValue = Number(obj.value)
      }
      else if(obj[key] == 'Mike') {
        mikeValue = Number(obj.value)
      }

      if(johnValue != mikeValue) {
        newData = {
          ...data,
          "Mike":  johnValue
        } 
      }
    }
  }
})

after whose execution I expected data like

const data = [{
        "name": "John",
        "value": "30"
    }, {
        "name": "Cindy",
        "value": "50"
    }, {
        "name": "Mathew",
        "value": "80"
    }, {
        "name": "Mike",
        "value": "30"
    }];

Is there a way to write it better using some of the ES6 features? Fiddle


Solution

  • Yes, you can do it a bit shorter

    const MikeRecordInd = data.findIndex(v => v.name === 'Mike')
    const JohnRecord = data.find(v => v.name === 'John')
    
    if (data[MikeRecordInd].value !== JohnRecord.value) {
      newData = [...data]
      newData[MikeRecordInd] = { name: 'Mike', value: JohnRecord.value }
    }