I have array of object listItem
, passing parameter paramId
Based on condition, when the id
in the the list is same with paramId
and having color as red
then next object (current val greater than val) value should be like
value, value + 1, value + 2, value + 3… and that current object val
become null
how to achieve this using for.. of loop using javascript
example 1
var paramId = 14
const listItem = [
{ id: 10, val: null, color: 'blue' },
{ id: 13, val: 1, color: 'black' },
{ id: 14, val: 2, color: 'red' },
{ id: 25, val: 3, color: 'yellow' },
{ id: 43, val: 5, color: 'green' },
];
Expected Output
[
{ id: 10, val: null, color: 'blue' },
{ id: 13, val: 1, color: 'black' },
{ id: 14, val: null, color: 'red' }, // change val to null
{ id: 25, val: 2, color: 'yellow' }, // 3 becomes 2 (val)
{ id: 43, val: 3, color: 'green' }, //5 becomes 3 (val + 1)
];
example 2
var paramId = 25
const listItem = [
{ id: 10, val: null, color: 'blue' },
{ id: 13, val: 1, color: 'black' },
{ id: 14, val: 2, color: 'yellow' },
{ id: 25, val: 3, color: 'red' },
{ id: 23, val: 4, color: 'green' },
{ id: 43, val: 5, color: 'green' },
];
Expected Output
[
{ id: 10, val: null, color: 'blue' },
{ id: 13, val: 1, color: 'black' },
{ id: 14, val: 2, color: 'yellow' },
{ id: 25, val: null, color: 'red' }, // changes val to null
{ id: 23, val: 3, color: 'green' }, // 4 becomes 3 (val)
{ id: 43, val: 4, color: 'green' }, // 5 becomes 4 (val+1)
];
Tried
const getByIdandColor = list.find(e=>e.id === paramId and e.color === 'red')
for (const item of listItem) {
if(item.id === paramId && item.color === 'red') {
...item,
val: null
} else if(item.color !== 'red' && item.id >= getByIdandColor.id) {
...item,
val: val +1
}
}
4
Answers
hey im not sure but i think you can handle it like that.
You have to call the val of the currenty item. Otherwise val will not be find and so you cant update any value of undefined ^^
The problem is your are not changing the value on the list, try this.
I have created a function which satisfies the expected results.
Here it goes like this.