Kindly help me to mutate the object in javascript. Lets say I have a below list of object, I want to objects if the keys are same in the first list Key "FOREFOOT - OUTER" repeated twice, value of this key different, in the first occurrence left is true and in the second occurrence right is true, I want this to be merges as "forefoot - outer" : {left: true, right: true}
[
{
"FOREFOOT - OUTER": {
"left": true,
"right": false
}
},
{
"FOREFOOT": {
"left": false,
"right": true
}
},
{
"FOREFOOT - INNER": {
"left": false,
"right": true
}
},
{
"FOREFOOT - OUTER": {
"left": false,
"right": true
}
},
]
Expected answer is
[
{
"FOREFOOT": {
"left": false,
"right": true
}
},
{
"FOREFOOT - INNER": {
"left": false,
"right": true
}
},
{
"FOREFOOT - OUTER": {
"left": true,
"right": true
}
},
]
Can anyone please help me to find a solution for this in javascript ES6.
You could do a little function like this :
const filterArray = (arrayToFilter) => {
const newArray = arrayToFilter;
let i = -1;
while (++i < newArray.length - 1) {
// So we brows the array since the start finally.
j = i;
while (++j < newArray.length) {
// We create a string to could use it in our if
const item_i = Object.keys(newArray[i]) + '';
const item_j = Object.keys(newArray[j]) + '';
// If the 2nd occure is true, then we put the 1st true
if (item_i == item_j) {
if (newArray[j][item_j].left)
newArray[i][item_i].left = true;
if (newArray[j][item_j].right)
newArray[i][item_i].right = true;
newArray.splice(j, 1);
// Seeing that we delete an element, we decrease our J
j--;
}
}
}
return newArray;
}
So this is in order to merges only "true" value. Because in your sample you merges only True value. If you want merges false too, edit the if with :
if (item_i == item_j) {
newArray[i][item_i].left = newArray[j][item_j].left;
newArray[i][item_i].right = newArray[j][item_j].right;
newArray.splice(j, 1);
j--;
}