I'm currently working on comparing the properties of objects by their keys. Here is some example data:
const data = [{
"name": "John",
"value": "30"
}, {
"name": "Cindy",
"value": "50"
}, {
"name": "Mathew",
"value": "80"
}, {
"name": "Mike",
"value": "35"
}];
The goal is to compare the values (value) of the names John and Mike. If Mike's value differs from John's, I want to update Mike's value with John's value. Below is a proposed 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
}
}
}
}
})
Once executed, I expect the data to be updated as shown below:
const data = [{
"name": "John",
"value": "30"
}, {
"name": "Cindy",
"value": "50"
}, {
"name": "Mathew",
"value": "80"
}, {
"name": "Mike",
"value": "30"
}];
Is there a more efficient way to accomplish this using ES6 features? Fiddle