[英]What is the most optimal way to convert Array to Object Array including array entries as object keys?
Consider the following two arrays:考虑以下两个 arrays:
var array=[
["2021-06-11", 100, 80, 70],
["2021-06-12", 101, 81, 71],
["2021-06-13", 102, 82, 72],
["2021-06-14", 103, 83, 73]]
var keyNames = ["date","a","b","c"];
Target:目标:
var newArray = [{date:"2021-06-11",a:100,b:80,c:70},
{date:"2021-06-12",a:101,b:81,c:71},
{date:"2021-06-13",a:102,b:82,c:72},
{date:"2021-06-14",a:103,b:83,c:73}]
What is the most optimal way to achieve this?实现这一目标的最佳方法是什么? can be done with forEach() or a combination with reduce / map prototyping?
可以使用forEach()或与reduce / map原型设计组合来完成吗?
I've tried with var obj = Object.assign({}, array)
but the result was index as keys我试过
var obj = Object.assign({}, array)
但结果是索引作为键
Any help will be appreciated!任何帮助将不胜感激! Thank you for your time!
感谢您的时间!
Can be done using map and forEach.可以使用 map 和 forEach 来完成。
let newArray = array.map((x) =>{ //map to convert the first array
let newObj = {};
let index =0;
keyNames.forEach((y) =>{ //forEach to loop through keynames
newObj[y] = x[index++];
});
return newObj;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.