I have an object of items in my variable this.rows
. There is a real-time item ing from the server which is identical to one which is inside in this.rows
object collection.
How to I replace an item with a new values ?
Here is an example:
let rows = [
{id: 11, active: 'no'},
{id: 22, active: 'yes'},
{id: 33, active: 'no'},
{id: 44, active: 'no'}
]
new_item = {id: 22, active:'yeah'};
rows.forEach(item => {
if (item.id === new_item.id) {
return new_item;
}
});
I have an object of items in my variable this.rows
. There is a real-time item ing from the server which is identical to one which is inside in this.rows
object collection.
How to I replace an item with a new values ?
Here is an example:
let rows = [
{id: 11, active: 'no'},
{id: 22, active: 'yes'},
{id: 33, active: 'no'},
{id: 44, active: 'no'}
]
new_item = {id: 22, active:'yeah'};
rows.forEach(item => {
if (item.id === new_item.id) {
return new_item;
}
});
Share
Improve this question
asked Jan 8, 2018 at 13:51
aspirinemagaaspirinemaga
3,93711 gold badges58 silver badges106 bronze badges
3
-
2
Did you already check what google suggests you: replace item in array javascript? It has some answers. Hint: splice. Or simply even
rows.map(item => item.id === new_item.id ? new_item : item)
. – dfsq Commented Jan 8, 2018 at 13:52 -
1
findIndex
to find if the item exists in the array, thensplice
to make the magic happen – tymeJV Commented Jan 8, 2018 at 13:53 -
Or
find()
andObject.assign()
to merge with existing – charlietfl Commented Jan 8, 2018 at 13:55
3 Answers
Reset to default 10Use the "findIndex" method to look for the index of the new item element in the rows array. Afterwards, check if a result was found (check if the index is greater than -1). Assign the item to the array using the position of the found element.
const indexOfItemInArray = rows.findIndex(q => q.id === new_item.id);
if (indexOfItemInArray > -1) {
rows[indexOfItemInArray] = new_item;
}
Or use the "splice" method:
const indexOfItemInArray = rows.findIndex(q => q.id === new_item.id);
rows.splice(indexOfItemInArray, 1, new_item);
To update easilly your array with a new value for specific id, use the map
function :
rows = rows.map((row) => {
if (row.id === new_item.id) {
row = new_item;
}
return row;
});
find item in rows and assign new item keys:
mutate rows:
_.chain(rows)
.find({ id: new_item.id })
.assign(new_item)
.value();
do not mutate rows:
const newRows = _.chain(rows)
.findIndex({ id: new_item.id })
.thru(index => _.chain(rows)
.cloneDeep()
.set(index, new_item)
.value()
)
.value();