【发布时间】:2020-05-10 19:50:40
【问题描述】:
我有一个带参数的函数,我正在执行一个 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)];,添加到 data(y) 的颜色是否总是从 red 开始,而不是仅仅被视为未定义?
【问题讨论】:
-
为什么不使用
name而不是带有['name']字符串的computed property name?你有输入想要输出的例子吗? -
@NinaScholz,我不确定你的意思
标签: javascript jquery arrays object ecmascript-6