我想知道是否有一个相对简单的方法来执行此操作,因为我可以使用以下内容:
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"]
var myobj = arr2.map(value => ({'Client': arr2[0], 'ActType': arr2[1], 'CallRepType': arr2[2]}));
但我连续3次获得相同的正确对象...我只想要一个返回的单个对象,如下所示:
{Client: 'ECF', ActType: 'Meeting', CallRepType: 'Call Report'}
我知道我可以遍历两个arrays
,但我希望使用map
获得解决方案,减少或利用javascript
中的点差......
答案 0 :(得分:2)
这是一个使用Array.reduce()
创建对象的解决方案:
const arr = [ "Client", "ActType", "CallRepType"];
const arr2 = [ "ECF", "Meeting", "Call Report"]
const myobj = arr.reduce((r, key, i) => {
r[key] = arr2[i];
return r;
}, {});
console.log(myobj);

答案 1 :(得分:2)
使用Array.prototype.forEach()
的更快的解决方案:
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"]
var result = {};
arr.forEach((el, i) => { result[el] = arr2[i]; });
console.log(result);
Array.prototype.forEach()`
答案 2 :(得分:0)
您可以遍历数组并执行此操作:
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"];
var len = arr.length;
var myObj = {};
for (var i = 0; i < len; i++) {
var myObject = {};
myObj[arr[i]] = arr2[i]
// myObj.push = myObject;
}
console.log(myObj);
&#13;