简体   繁体   中英

How to create an object from 2 arrays of same length

I am trying to create an object from 2 arrays.

var arr1 = ["2000", "10003", "1234000", "44444444", "9999", "11", "11", "22", "123"];
var arr2 = [2, 4, 10, 32, 36, 2, 2, 4, 6];

I used a for loop to populate the object:

var obj= {};

for(var i = 0; i < arr1.length; i++) { 
    obj[arr1[i]] = arr2[i]; 
}

Result:

[object Object] {
  10003: 4,
  11: 2,
  123: 6,
  1234000: 10,
  2000: 2,
  22: 4,
  44444444: 32,
  9999: 36
}

It does create the object based on my 2 arrays, but omit 1 value that is a duplicate in the arrays. I don't want to exclude them. What could be the trick to include ALL the array element in my object? The result is not even in the same order as the original arrays...

Thank you!

populate the values into array if that could be a workaround for you..

var obj= [];
for(var i = 0; i < arr1.length; i++) { 
  var obj1 ={};
  obj1[arr1[i]] = arr2[i];           
  obj.push(obj1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM