如何从多个数组创建对象数组 [英] How to create an array of objects from multiple arrays
本文介绍了如何从多个数组创建对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下数组:
var ids = [1,2,3]; //Hundreds of elements here
var names = ["john","doe","foo"]; //Hundreds of elements here
var countries = ["AU","USA,"USA"]; //Hundreds of elements here
在性能方面生成具有与此类似结构的对象数组的最佳方法是什么:
What's the best way performance-wise to generate an array of objects with a similar structure to this:
var items = [
{id:1,name:"john",country:"AU"},
{id:2,name:"doe",country:"USA"},
...
];
推荐答案
您应该能够简单地映射所有 ID,保留对索引的引用,并基于该索引构建您的对象.
You should be able to simply map through all ids, keeping a reference to your index, and build your object based on that index.
var items = ids.map((id, index) => {
return {
id: id,
name: names[index],
country: countries[index]
}
});
这篇关于如何从多个数组创建对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文