I have a JSON array which looks like this –
[
{name: 'Alex', date: '05/17/2023 10:32 PM', id: '00153168', priority: '3-Medium'},
{name: 'Peter', date: '05/17/2023 11:32 PM', id: '00153169', priority: '3-Medium'}
]
Expected :
{
name : ['Alex','Peter'],
date : ['05/17/2023 10:32 PM','05/17/2023 11:32 PM'],
id: ['00153168','00153169'],
priority: ['3-Medium', '3-Medium']
}
Here is the attempt I made –
let arr = [];
data.forEach((number, index, array) => {
let keys = Object.keys(array[index]);
for(i in keys){
let a = data.map(item => item[keys[i]]);
let b = keys[i];
arr.push({b:a});
}
console.log(arr);
});
Any help should be appreciated. Thanks!
3
Answers
If you know for sure that the shape of all of the objects in your array are uniform, you can first get the keys of your final data with the first element in your array.
Then just loop over your keys. Grabbing all of the values for each of those keys on every iteration. You can use map to access nested elements even in a complex object. Once you have the values, you can add them to a new object.
When you iterated over all your keys, you should have the data in the shape you need.
You might use
reduce
: