如何循环遍历多个数组并且"配对"他们在宣布一个物体时?假设有两个数组包含相同数量的数据。我想映射每一个并分配给对象属性。
这就是我想要实现的目标:
{
name: john,
surname: doe,
datasets: [{
data: 1,
vehicle: car,
color: red
},
{
data: 2,
vehicle: car,
color: blue,
},
{
data: 3,
vehicle: car,
color: green
}]
}
这就是我所做的:
function Constructor (name, surname, data, vehicle, colors) {
this.name = name;
this.surname = surname;
this.data = data;
this.vehicle = vehicle;
this.colors = colors;
this.person = {
name: name,
surname: surname,
datasets: [{
data: data.map(data => ({
data,
vehicle: vehicle,
color: colors.map(color => ({
color
}))
})),
}]
}
};
var testing = new Constructor ('john', 'doe', [1,2,3], 'car', ['red', 'blue', 'green']);
console.log (testing.person);
答案 0 :(得分:2)
如果data
和color
总是具有相同的长度,则可以在map函数中使用index
,它将作为第二个参数传递:
data.map((data, i) => ({
data,
vehicle: vehicle,
color: colors[i]
})
)
对于不匹配的数据集(即:一个数据集比另一个数据集更多),您可以采取多种方法。
使用默认颜色(如果data
有更多项目):
data.map((data, i) => ({
// ...
color: colors[i] || "black"
})
如果数据集未对齐,则抛出错误:
if (data.length !== colors.length) throw "data length does not match color length";
获取最短的数据集并丢弃额外的数据
Array.from(
{ length: Math.min(data.length, colors.length) },
(_, i) => ({
data: data[i], color: colors[i], vehicle
})
);
当然还有更多!
答案 1 :(得分:1)
我将提出一个您可能没有想到的替代解决方案。如果colors.length <= data.length
始终为true
,您可以考虑使用%
余数运算符循环显示颜色,如下所示:
data.map((data, i) => ({
data,
vehicle: vehicle,
color: colors[i % colors.length]
})
function Constructor(name, surname, data, vehicle, colors) {
this.name = name;
this.surname = surname;
this.data = data;
this.vehicle = vehicle;
this.colors = colors;
this.person = {
name: name,
surname: surname,
datasets: [{
data: data.map((data, i) => ({
data,
vehicle: vehicle,
color: colors[i % colors.length]
}))
}]
}
}
var testing = new Constructor('john', 'doe', [1, 2, 3, 4, 5], 'car', ['red', 'blue', 'green']);
console.log(testing.person);
为red, blue, green, red, blue
data.length === 5