Home > OS >  How to map out two arrays into array of object
How to map out two arrays into array of object

Time:10-01

I have two arrays

keys:[key0, key1, key2, key3]

and

body:[['jake', 24, 3, true], ['susan', 21, 0, true]]

the result I need is

[{key0:jake, key1:24, key2:3, key3:true}, {key0:susan, key1:21, key2:0, key3:true}]

CodePudding user response:

Map the keys and values to an arrays of pairs of [key, value], and then convert to an object using Object.fromEntries() (see zipObject function).

To convert an array of values, use Array.map() with zipObject:

const zipObject = keys => values => Object.fromEntries(keys.map((key, i) => [key, values[i]]))

const keys = ['key0', 'key1', 'key2', 'key3']

const values = [['jake', 24, 3, true], ['susan', 21, 0, true]]

const result = values.map(zipObject(keys))

console.log(result)

CodePudding user response:

const body = [['jake', 24, 3, true], ['susan', 21, 0, true]];
const keys = ['key0', 'key1', 'key2', 'key3']
let newArray = [];

numbers.forEach((value) =>
{
    let obj={};
    keys.forEach((key,index) => 
{
        obj[`${key}`] = value[index];
        
    })
    newArray.push(obj);
    
});
console.log(newArray)

CodePudding user response:

This may be one simple way to do this, using easy to read loops:

const keys = ['key0', 'key1', 'key2', 'key3'];
const body = [['jake', 24, 3, true], ['susan', 21, 0, true]];
const result = [];
for (let b of body) {
    const obj = {};
    for (let i = 0; i < b.length; i  ) {
        obj[keys[i]] = b[i];
    }
    result.push(obj);
}
console.log(result);

Result:

[
  { key0: 'jake', key1: 24, key2: 3, key3: true },
  { key0: 'susan', key1: 21, key2: 0, key3: true }
]
  • Related