R
R
reactreact2016-01-29 19:36:53
JavaScript
reactreact, 2016-01-29 19:36:53

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}
    ];

And there is such an array with objects:
this.items = [
      {name : 'Dima', id: 3},
      {name : 'Lena', id: 5},
    ];

So: if in the first array the objects have the same id from another array with the objects, then in the first one you need to replace active: false with active: true. That is, based on the arrays above, you need to get the following result:
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}
    ];

What is the best way to do this? Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2016-01-29
@reactreact

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;
        }
    });

A
Andrey Dyrkov, 2016-01-29
@VIKINGVyksa

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 question

Ask a Question

731 491 924 answers to any question