0

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}]

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0
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)

Comments

0

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 }
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.