[英]Javascript two array merge( key and value)
I have two array. 我有两个数组。 I want to merge this two arrays into one array. 我想将这两个数组合并为一个数组。 One array consisting keys and another one values.My array looks like 一个数组由键和另一个值组成,我的数组看起来像
productId = [8,7,9];//Key Element
quantity = ["5","1","3"];//Value Element
//expected new array
newarray = {
"8": 5,
"7": 1,
"9": 3
}
I already tried to merge these arrays, in this way 我已经尝试过以这种方式合并这些数组
var newArray = {};
for(var i=0; i< productId.length; i++){
newArray[productId[i]] = quantity [i];
}
console.log(newArray);
It returns 它返回
Object [ <7 empty slots>, "5", "1", "3" ]
Try the following: 请尝试以下操作:
var productId = [8,7,9];//Key Element var quantity = ["5","1","3"];//Value Element var obj = {}; var i = 0; for(var k of productId) { obj[k] = parseInt(quantity[i]); i++; } console.log(obj);
You are working in firefox so you may get this type of issue because the problem might be caused at how Firefox' console.log has interpreted the input object. 您在firefox中工作,因此可能会遇到此类问题,因为该问题可能是由Firefox的console.log解释输入对象的方式引起的。
Please look here 请看这里
Empty slots in JavaScript objects? JavaScript对象中的空插槽?
Try this 尝试这个
var productId = [8,7,9]; var quantity = ["5","1","3"]; var newarray = {}; productId.forEach((key, i) => newarray[key] = quantity[i]); console.log(newarray);
Your new "array" is not an Array
but an Object
. 您的新“数组”不是Array
而是Object
。
You can iterate on one of the arrays using Array.reduce
to construct the object. 您可以使用Array.reduce
遍历一个数组Array.reduce
构造对象。
Something like that: 像这样:
const arr1 = ['8', '2', '4']; const arr2 = ['28', '12', '45']; const result = arr1.reduce((obj, currentItem, index) => { obj[currentItem] = arr2[index]; return obj; }, {}); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.