我有一个带有params的函数,并且正在执行forEach循环以添加循环中的所有值。
const data = (sd) => Object.entries(obj).map(([k, g]) => ({
['name']: k,
['data']: g.map(entry => entry[sd]),
['type']: sd
}));
然后我将它们压成一个巨大的阵列:
let arr = ['abc', 'xyz'];
let x = [];
arr.forEach(y => {
x = [...x, ...data(y)];
});
我还想向data
添加另一个键值对。我希望值来自数组:
color_array = ['red', 'blue', 'green']
所以我做到了:
const data = (sd) => Object.entries(obj).map(([k, g]) => ({
['name']: k,
['data']: g.map(entry => entry[sd]),
['type']: sd,
['color']: color_arr[i++]
}));
输出:
color: "red"
data: (3) [1, 2, 3]
name: "Jim"
type: "Manager"
color: "blue"
data: (3) [1, 2, 3]
name: "Steve"
type: "Manager"
color: "green"
data: (3) [1, 2, 3]
name: "John"
type: "Manager"
--------------------NEW SET----------------
color: undefined
data: (3) [1, 2, 3]
name: "John"
type: "CEO"
color: undefined
data: (3) [1, 2, 3]
name: "John"
type: "COO"
执行此操作时,由于数组中只有5个元素,因此其余值将变为undefined
。我有什么办法可以从数组中添加元素以从color_arr的开头开始?
我的意思是,对于每个x = [...x, ...data(y)];
,添加到数据(y)的颜色是否总是从red
开始,而不是仅仅被定义为未定义?
答案 0 :(得分:1)
您可以使用模数来遍历颜色数组中的值。也就是说,剩下的就是将计数器除以颜色数组的长度。
const color_array = ['red', 'blue', 'green', 'black', 'white'];
let i = 0;
for (j = 0; j < 20; j++) {
console.log(color_array[i++ % color_array.length]);
}
未经测试的代码版本:
const data = (sd) => Object.entries(obj).map(([k, g]) => ({
['name']: k,
['data']: g.map(entry => entry[sd]),
['type']: sd,
['color']: color_array[i++ % color_array.length]
}));
有关%
运算符的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder