Issue
This Content is from Stack Overflow. Question asked by Oliver
I have the following object that I would like to convert it into an array of object and each object from the array to have the key: value[0].
object:
const obj = {
comedy: ['book1', 'book2'],
action: ['book3', 'book4'],
drama: ['book5'],
}
output
const arr = [
{comedy: 'book1'},
{comedy: 'book2'},
{action: 'book3'},
{action: 'book4'},
{drama: 'book5'},
]
So far I have tried solving this with loops and using Object.entries
. But I do not get the output I need.
let result = [];
for(const [key1, value1] of Object.entries(arr)) {
for (const [key2, value2] of Object.entries(value1)) {
if(result[key2]) {
result[key2] [key1] = value2
} else {
result[key2] = {[key1]: value2}
}
}
}
console.log(result)
I have also tried to loop recalling the function inside itself. (I have found this search for the answer). But it will get stucked in a infinite loop.
const result = [];
const getArray = (obj) => {
if (!obj) return;
const {keys, ...rest} = obj;
result.push({...rest});
getArray(keys);
}
console.log('here', getArray(arr));
Solution
You could use a reduce over the entries of obj
, adding objects to the accumulator for each entry in the array value:
const obj = {
comedy: ['book1', 'book2'],
action: ['book3', 'book4'],
drama: ['book5'],
}
const arr = Object.entries(obj)
.reduce((acc, [k, v]) => acc.concat(v.map(b => ({ [k] : b }))),
[]
)
console.log(arr)
This Question was asked in StackOverflow by Oliver and Answered by Nick It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.