TransWikia.com

Convert object of arrays to array of objects

Stack Overflow Asked by drmrbrewer on December 5, 2020

I have source data in the following format (object of arrays):

{
    value: [
      59, 58, 62, 58, 56, 57, 57, 65, 81, 81
    ],
    dayOfWeek: [
      'Thursday', 'Friday', 'Saturday', 'Thursday', 'Friday', 'Friday',
      'Friday',   'Monday', 'Friday',   'Tuesday'
    ],
    dayOrNight: [
      'N', 'D', 'N', 'D', 'D', 'N', 'N', 'N', 'N', 'N'
    ]
}

And I want the data transformed into the following format (array of objects):

[
    {
        value: 59,
        dayOfWeek: 'Thursday',
        dayOrNight: 'N'
    },
    {
        value: 58,
        dayOfWeek: 'Friday',
        dayOrNight: 'D'
    },
    {
        value: 62,
        dayOfWeek: 'Saturday',
        dayOrNight: 'N'
    },
    ...
]

This is kinda the opposite of this question.

What is the appropriate combination of commands to do this, whether using e.g. lodash or otherwise?

One Answer

Combining map method and accessing by key to object, we can achieve desired result:

data.value.map((s, i) => ({value: s, 
   dayOfWeek: data.dayOfWeek[i], dayOrNight: data.dayOrNight[i]}));

An example:

let data = {
    value: [
      59, 58, 62, 58, 56, 57, 57, 65, 81, 81
    ],
    dayOfWeek: [
      'Thursday', 'Friday', 'Saturday', 'Thursday', 'Friday', 'Friday',
      'Friday',   'Monday', 'Friday',   'Tuesday'
    ],
    dayOrNight: [
      'N', 'D', 'N', 'D', 'D', 'N', 'N', 'N', 'N', 'N'
    ]
};

const result = data.value.map((s, i) => ({value: s, 
   dayOfWeek: data.dayOfWeek[i], dayOrNight: data.dayOrNight[i]}));
console.log(result);

UPDATE:

This is slightly modified your approach:

let data = {
    value: [
      59, 58, 62, 58, 56, 57, 57, 65, 81, 81
    ],
    dayOfWeek: [
      'Thursday', 'Friday', 'Saturday', 'Thursday', 'Friday', 'Friday',
      'Friday',   'Monday', 'Friday',   'Tuesday'
    ],
    dayOrNight: [
      'N', 'D', 'N', 'D', 'D', 'N', 'N', 'N', 'N', 'N'
    ]
};

const result = Object.values(data)[0].map((s, i) => {
    let obj = {};
    for (let key in data) {
            obj[key] = data[key][i];
    }
    return obj;
});
console.log(result);

Correct answer by StepUp on December 5, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP