Created
December 1, 2018 20:33
-
-
Save hamatoyogi/4c715e21870323870e94032a68d0318b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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