skip to Main Content

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


  1. 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.

    const data = [
     {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'}
    ]
    
    
    const keys = Object.keys(data.at(0));
    let consolidatedObject = {};
    
    for (const key of keys){
      const keyData = data.map(x => x?.[key])
      consolidatedObject = {
        ...consolidatedObject,
        [key]: keyData
      }
    }
    
    console.log(consolidatedObject)
    Login or Signup to reply.
  2. You might use reduce:

    const arr = [
     {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'}
    ];
    
    const o = arr.reduce((a, e) => {
      for (let k in e) {
        a[k] = a[k] || [];
        a[k].push(e[k]);
      }
      return a;
    }, {});
    
    console.log(o)
    Login or Signup to reply.
  3. const data = [
     {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'}
    ]
    
    const result = data.reduce((a,c) => 
      (Object.entries(c).forEach(([k,v]) => (a[k]??=[]).push(v)), a), {})
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search