Answer the question
In order to leave comments, you need to log in
How to change the value of an object's property depending on another object?
There is an array with objects, let's say:
this.items = [
{name : 'Petya', id: 1, active: false},
{name : 'Vasjya', id: 2, active: false},
{name : 'Dima', id: 3, active: false},
{name : 'Lena', id: 4, active: false},
{name : 'Katya', id: 5, active: false}
];
this.items = [
{name : 'Dima', id: 3},
{name : 'Lena', id: 5},
];
this.items = [
{name : 'Petya', id: 1, active: false},
{name : 'Vasjya', id: 2, active: false},
{name : 'Dima', id: 3, active: true},
{name : 'Lena', id: 4, active: false},
{name : 'Katya', id: 5, active: true}
];
Answer the question
In order to leave comments, you need to log in
You can use indexBy from lodash / underscore for the first array, this helper will convert the array into an object using a specific field from the objects nested in the array as keys.
Since objects in js are passed by reference, the objects in the index and in the array will be connected.
After we run through the second array loop and change the values in the first one
Like this:
this.items = [
{name : 'Petya', id: 1, active: false},
{name : 'Vasjya', id: 2, active: false},
{name : 'Dima', id: 3, active: false},
{name : 'Lena', id: 4, active: false},
{name : 'Katya', id: 5, active: false}
];
this.itemsIndex = _.indexBy(this.items, 'id');
this.items2 = [
{name : 'Dima', id: 3},
{name : 'Lena', id: 5},
];
this.items2.forEach(el => {
if(el.id in this.itemsIndex) {
this.itemsIndex[el.id].active = true;
}
});
An ordinary array in an array, if you do it differently, you will need to change the original arrays
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question