I have the following javascript Object
const items = {
0: {
id: 1,
color: 'blue'
},
1: {
id: 2,
color: 'red'
}
}
I am trying to restructure it so that the keys have an indexed numerical value like so: item1id, item1color, item2id, item2color. Or to be more precise it should look like this in the end:
const restrucuturedItems = {
item1id: 1,
item1color: 'blue',
item2id: 2,
item2color: 'red'
}
I have tried the following, but so far didn't yield positive results:
const restrucuturedItems = {}; // should collect the restructured data in one object like so: {item1id: 1, item1color: 'blue', item2id:2, item2color: 'red'}
const restructuredData = Object.keys(items).forEach(key => {
let i = parseInt(key, 10) + 1;
let item = {
item[i]id: 1, // this part is incorrect. it should produce item1id, item2id
item[i]color: 'blue' // this part is incorrect. it should produce item1color, item2color
}
restrucuturedItems.push(item);
});
After hours of research, I still don't know how to write this part correctly.
You shouldn't use push
because you want your restrucuturedItems
to be an object, not an array.
Concatenate the i
with the id or color inside the brackets, and use two Object.entries
- one to get the keys and values of each object in the outer object, and one to get the keys and values of each inner object:
const items = {
0: {
id: 1,
color: 'blue'
},
1: {
id: 2,
color: 'red'
}
}
console.log(Object.entries(items).reduce((a, [num, obj]) => {
Object.entries(obj).forEach(([key, val]) => {
a['item' + num + key] = val;
});
return a;
}, {}));
If you really wanted to start at item1id
rather than item0id
, then increment num
initially:
const items = {
0: {
id: 1,
color: 'blue'
},
1: {
id: 2,
color: 'red'
}
}
console.log(Object.entries(items).reduce((a, [num, obj]) => {
num++;
Object.entries(obj).forEach(([key, val]) => {
a['item' + num + key] = val;
});
return a;
}, {}));