6

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?

000
  • 26,951
  • 10
  • 71
  • 101
GGw
  • 413
  • 5
  • 18
  • This function is called "zip". The difficult part of solving a problem is not knowing what words to look for :) – 000 Nov 27 '17 at 18:30
  • 1
    Does this answer your question? [Create an object from an array of keys and an array of values](/q/39127989/90527) – outis Sep 01 '22 at 07:54

5 Answers5

15

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Hum. I guess that this answer should be considered as the best henceforth. Why not otherwise (?) – keepAlive May 07 '19 at 14:48
  • It works for the question as asked, but isn't generically applicable. With a large number of keys the spread operator could exceed the JS engine's argument length limit. That should be in the 10s of thousands though: https://stackoverflow.com/a/22747272/322333 – boycy Oct 20 '20 at 11:13
  • the first solution doesnt work in Typescript `A spread argument must either have a tuple type or be passed to a rest parameter.` You have to pass in the first parameter like so `Object.assign({}, ...keys.map((k, i) => ({ [k]: values[i] })));` – Xitcod13 Jan 14 '22 at 21:03
  • @Xitcod13, this answer is in javascript. for typescript, it could be different. – Nina Scholz Jan 14 '22 at 22:54
  • It's not really a critique of the answer I just posting it here for people that come in the future. It can be hard to figure this stuff out when it's not really obvious. – Xitcod13 Jan 14 '22 at 23:17
6

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)
brk
  • 48,835
  • 10
  • 56
  • 78
  • yep! your'e the first one still waiting for 6 minutes to mark it! thanks again brother! – GGw Nov 27 '17 at 18:35
2

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);
zfrisch
  • 8,474
  • 1
  • 22
  • 34
1
const keys = ['name', 'age'];
const vals = ['anna', 20];

keys.reduce((o, e, i) => ((o[e] = vals[i]), o), {});
// {name: 'anna', age: 20}
Boy
  • 19
  • 3
  • 3
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – jasie Jan 18 '21 at 10:24
  • @Boy: is it possible to get some insight into what the callback function body is doing here? I assume the `o` is added after the assignment expression to act as the return value, but I'm not familiar with the syntax. My understanding from the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#syntax) is that arrow functions must use `{` `}` when they contain statements rather than a single expression, but it looks like you are using statements `((o[e] = vals[i]), o)` and it works. Do you know where this behaviour is described (or anyone else)? – teepee Feb 06 '23 at 21:54
0

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 }
Tomislav Stankovic
  • 3,080
  • 17
  • 35
  • 42
tokun
  • 51
  • 3