Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const arbitraryDataList = [{
rootId: 'false'
},
{
root: {
field1: 'val1'
}
},
{
root: {
field2: 'val2'
}
},
{
root2: {
field2: 'val2'
}
},
{
root2: {
field2: 'val2',
fieldaaaa: {
fielda: 'valaaaa'
}
}
}
];
const reduceListToJSObject = (someList) => someList.reduce((accumulator, currentValue, currentIndex, array) => {
const rootKeys = Object.keys(currentValue);
console.log(currentValue);
if (rootKeys.length > 0) {
for (let i = 0; i < rootKeys.length; i++) {
const currentKeyVal = rootKeys[i];
const value = currentValue[rootKeys[i]];
const currentKey = rootKeys[i];
console.log(value);
console.log('typof key ===>', typeof value);
console.log('currentKey ===>', currentKey);
switch (typeof value) {
case 'string':
accumulator[currentKey] = value;
// return accumulator;
console.log('accumulator ===>', accumulator);
break;
case 'object':
// do something;
if (accumulator.hasOwnProperty(currentKey)) {
console.log('i have this key already: ', currentKey);
console.log('time to merge');
console.log('accumulator[currentKey] ===>', accumulator[currentKey]);
console.log('value :', value);
const mergedObj = {
...accumulator[currentKey],
...value
};
console.log('mergedObj ===>', mergedObj);
accumulator[currentKey] = mergedObj;
} else {
accumulator[currentKey] = value;
}
console.log('accumulator ===>', accumulator);
break;
}
}
}
console.log(accumulator);
return accumulator;
}, {});
const expectedOutput = reduceListToJSObject(arbitraryDataList);
console.log('expectedOutput ===>', expectedOutput);
const obj1 = {
a: 'a',
b: 'b'
};
const obj2 = {
c: 'c',
a: 'yuval'
};
// const newObj = Object.assign({}, obj1, obj2);
const newObj = { ...obj1,
...obj2
};
console.log('newObj ===>', newObj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment