cocoPuffs
cocoPuffs

Reputation: 669

How do you append an array of keys to object?

I have an array of strings and a params object like this. How do I create the params constant? Using either forEach, map, and or filter?

key = ['dog', 'car', 'cat'];
value = [ 3, 1, 2 ];

    const params = {
       item: {
           [key]: value[0],
           // more keys to be appended
       }
    }

Upvotes: 1

Views: 53

Answers (3)

FisNaN
FisNaN

Reputation: 2865

Just looping through each value:

const key = ['dog', 'car', 'cat'];
const value = [ 3, 1, 2 ];

const item = {};
key.forEach((k, i) => { item[k] = value[i]; });

const parmas = {};
parmas.item = item;
console.log(parmas);

Upvotes: 1

kshetline
kshetline

Reputation: 13682

You could do it this way:

value.reduce((acc, val, index) => (acc[key[index]] = val, acc), {});

This produces:

{dog: 3, car: 1, cat: 2}

Upvotes: 0

Paulo Moreno
Paulo Moreno

Reputation: 141

You can set an object's keys using the following syntax:

obj[key] = value

So in you case, you could do something like:

key = ['dog', 'car', 'cat'];
value = [ 3, 1, 2 ];

var params = {
    item : {}
}

for (var i=0; i<key.length;i++){
    params.item[key[i]] = value[i];
}

Upvotes: 0

Related Questions