[英]Create object from two arrays
How can I create an object from two arrays without using loops in javascript. 如何在不使用javascript循环的情况下从两个数组创建对象。
example: 例:
array1 = [1,2,3,4,5];
array2 = [A,B,C,D,E];
I want from below object 我想从下面的对象
obj = {
'1': 'A',
'2': 'B',
'3': 'C',
'4': 'D',
'5': 'E',
}
Thanks in advance 提前致谢
var obj = {} array1 = [1, 2, 3, 4, 5]; array2 = ['A', 'B', 'C', 'D', 'E']; array1.forEach(function(value, index) { obj[value] = array2[index]; }); console.log(obj);
An ES6, array reduce solution. ES6,阵列减少解决方案。
const array1 = [1, 2, 3, 4, 5]; const array2 = ['A', 'B', 'C', 'D', 'E']; const resultMap = array1.reduce( (accumulator, value, index) => Object.assign(accumulator, { [value]: array2[index], }), {} ); console.log(resultMap);
just for fun created something like this without using any iteration methods. 只是为了好玩而不使用任何迭代方法创建这样的东西。
const array1 = [1,2,3,4,5];
const array2 = ['A','B','C','D','E'];
let combineKeyValueProxy = new Proxy({}, {
set: function(target, prop, value, receiver) {
target[array1[prop]] = value;
return true
}
});
const output = Object.assign(combineKeyValueProxy, array2);
console.log(output) // Proxy {1: "A", 2: "B", 3: "C", 4: "D", 5: "E"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.