0

I have an Array of Items. Each Item in the Array, has a set of Properties. One of them is called config: object[]. It is an array of Objects.

Normally, I provide the full object with the correct config array of objects, but for some of my tests, I want to pass different config options. For example wrong config array, empty array etc..

Here is my code:

    const connectionResources = [Array.forEach(object => object.config === [])]
    connectionResources.forEach(builtInOptions => console.log(builtInOptions))

This is what I tried. I tried to spread the Array, but no luck there as well.

Can someone help me a little bit here? I basically want my Array of Objects to have an empty config array property instead of the original object.. How to do that?

2 Answers2

1

Example data

let resources = [{
    config: [{}, {}]
}, {
    config: [{}, {}]
}];

Empty config property

resources = resources.map(resource => {
    resource.config = [];
    return resource;
});
  • Thank you that worked.. One more thing. Is there a way to achieve the same result, with directly mutating the object? I am getting this eslint rule which I can totally disable, `no-param-reassign`, but just asking. –  Oct 17 '19 at 14:20
  • @DimitrisEfst yes, see my answer – junvar Oct 17 '19 at 14:22
1

I tried to spread the Array, but no luck there as well.

Firstly, if you want to spread an array, you must use the spread operator; e.g. ...myArray.

Array.forEach

Secondly, Array.prototype.forEach returns undefined, and Array.forEach is undefined (unless you've named your array Array, which you shouldn't since that would shadow the Array class).

Now to the point, what you need is essentially 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);
junvar
  • 11,151
  • 2
  • 30
  • 46