I have two arrays of objects, that look like this:
const data = [
{
id: 1,
condition: 1,
helpers: [{id: 1, condition: null}, {id: 2, condition: 2}]
},
{
id: 2,
condition: null,
helpers: [{id: 1, condition: 1}, {id: 2, condition: null}]
}
]
const conds = [
{
id: 1,
conditions: {
rules: ['test', 'foo']
}
},
{
id: 2,
conditions: {
rules: ['#hashtag', 'foo']
}
}
]
What I try to achieve is, that I want to replace the condition
values of the data
array with the ones in the conds
array.
My solution, which does not work quite well looks like this:
let newArray = [];
data.forEach(obj => {
conds.forEach(cond => {
if (obj.condition) {
if (obj.condition === cond.id) {
obj.condition = cond.conditions.rules;
newArray.push(obj);
}
} else {
obj.helpers.forEach(h => {
if (h.condition && h.condition === cond.id) {
h.condition = cond.conditions.rules;
newArray.push(obj);
}
});
}
})
});
I feel like I am pretty close to the solution since my newArray
contains the changes properties, but not for the last item inside of helpers, whereas the condition
property is still 2.
The output should look like this:
[
{
id: 1
condition: ['test', 'foo'],
helpers: [{id: 1, condition: null}, {id: 2, condition: ['#hashtag', 'foo']}]
},
{
id: 2
condition: null,
helpers: [{id: 1, condition: ['test', 'foo']}, {id: 2, condition: null}]
},
]
What am I missing here?