我有一个带有参数的函数,我正在执行一个 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 = ['红色', '蓝色', '绿色']
所以我做到了:
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 个元素,因此其余值将变为未定义
。有什么方法可以让我从数组中添加元素以从 color_arr 的开头开始吗?
我的意思是,对于每个 x = [...x, ...data(y)];
,添加到 data(y) 的颜色是否可以始终从 开始红色
,而不是仅仅被视为未定义?
最佳答案
您可以使用模来循环颜色数组中的值。也就是说,计数器除以颜色数组的长度所得的余数。
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
关于javascript - 从数组向对象添加值,并且当数组用完时不会变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61717888/