javascript - 在 JS 中用不同的数组替换对象数组

标签 javascript arrays typescript spread

我有一系列元素。数组中的每个项目都有一组属性。其中之一称为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/

相关文章:

reactjs - React Typescript 中的类型 'elements' 上不存在属性 'EventTarget'

reactjs - react 谷歌地图 : Cannot find namespace 'google'

javascript - Createjs - Tweenjs 不适用于位图

javascript - 调用函数的内部变量

javascript - 完全摧毁物体

java - 如何处理 org.tensorflow.lite.Interpreter.runForMultipleInputsOutputs() 的结果

c - 这个排序算法的大O

javascript - 如何将事件处理程序绑定(bind)到 Google Maps V3 API 默认 PanControl 的点击事件?

javascript - 将包含字符的字符串拆分为数组项

javascript - typescript 对象奇怪的类型语法