我有一系列元素。数组中的每个项目都有一组属性。其中之一称为config:object[]
。它是一个对象数组。
通常,我会为完整的对象提供正确的config
对象数组,但对于我的一些测试,我想传递不同的配置选项。例如错误的配置数组
、空数组
等..
这是我的代码:
const connectionResources = [Array.forEach(object => object.config === [])]
connectionResources.forEach(builtInOptions => console.log(builtInOptions))
这是我尝试过的。我尝试传播数组,但也没有成功。
有人可以帮我一点吗?我基本上希望我的对象数组有一个空的配置数组属性而不是原始对象。如何做到这一点?
最佳答案
I tried to spread the Array, but no luck there as well.
首先,如果要扩展数组,必须使用扩展运算符;例如...myArray
.
Array.forEach
其次,Array.prototype.forEach
返回 undefined
,而Array.forEach
是 undefined
(除非您已将数组命名为 Array
,但您不应该这样做,因为这会遮蔽 Array
类)。
现在,您需要的基本上是 Array.prototype.map
let original = [{a: 3, config: [4, 5], b: 6}, {a: 13, config: [14, 15], b: 16}];
let emptyConfig = original.map(o => ({...o, config: []}));
let hundredConfig = original.map(o => ({...o, config: [100, 101, 102]}));
console.log(original);
console.log(emptyConfig);
console.log(hundredConfig);
关于javascript - 在 JS 中用不同的数组替换对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434667/