Zip arrays as keys and values of an Object

Viewed 4138

I have this data

 var foo = ['US','MX','NZ'];
 var foo1 = [12',13',17];


 var Object = {};

Ive tried this thing

 var Object = {foo:foo1}

but it is not working when i arrayed the object using alert (JSON.stringify(Object)); i saw:

 {"foo":["12","13","17"]}

what I want is that make it like this:

var Object = {
  "US":"12",
  "MX":"13",
  "NZ":17
}

is there any way I could make it looked like this?

5 Answers

You could map the objects for a single object with Object.assign.

var keys = ['US', 'MX', 'NZ'],
    values = ['12', '13', '17'],
    object = Object.assign(...keys.map((k, i) => ({ [k]: values[i] })));

console.log(object);

A newer approach with Object.fromEntries

var keys = ['US', 'MX', 'NZ'],
    values = ['12', '13', '17'],
    object = Object.fromEntries(keys.map((k, i) => [k, values[i]]));

console.log(object);

Iterate over any one array using forEach and use the index to retrieve the element from second array.Also note the usage of square [] braces & the variable is named as obj(it can be anything) but avoided Object

var foo = ['US', 'MX', 'NZ'];
var foo1 = [12, '13', 17];


var obj = {};
foo.forEach(function(item, index) {
  obj[item] = foo1[index]

});
console.log(obj)

Try this:

     let keys = ['US','MX','NZ'],
     values = [12,13,17], 
     myObject = {};
     for(let i = 0; i < keys.length; i++) myObject[keys[i]] = values[i];

     let keys = ['US','MX','NZ'],
     values = [12,13,17], 
     myObject = {};
     for(let i = 0; i < keys.length; i++) myObject[keys[i]] = values[i];
    

     console.log(myObject);

const keys = ['name', 'age'];
const vals = ['anna', 20];

keys.reduce((o, e, i) => ((o[e] = vals[i]), o), {});
// {name: 'anna', age: 20}

Boy's answer is very concise, but it took me a bit to figure out why it worked. Here's an explanation with some tweaks.

const keys = ['name', 'age'];
const vals = ['anna', 20];

keys.reduce((newArray, key, index) => ((newArray[key] = vals[index]), newArray), {});

Setting {} as the last parameter of the reduce function creates a new array that is used as the initial value. Every subsequent iteration has the newArray passed to it as the previous value. If this wasn't specified, then each iteration would produce a different array with only one key:value pair.

newArray: {}
key: name
index: 0
values[index]: anna
* ---------------------- *
newArray: {"name":"anna"}
key: age
index: 1
values[index]: 20
* ---------------------- *
{ name: 'anna', age: 20 }
Related