Search code examples
javascriptecmascript-6ecmascript-2016

How to set an Object's values inside an array with ES6?


I'm looking for the quickest and most resource friendly way of setting an Object's values inside an array. Can use ES6 syntax as well.

So let's say I have this array of objects:

let group = [
    {
        id: 1,
        name: 'Test 1',
        geo: 'Japan',
        car: 'Toyota'
    },
    {
        id: 2,
        name: 'Test 2',
        geo: 'USA',
        car: 'Tesla'
    },
    {
        id: 3,
        name: 'Test 3',
        geo: 'Germany',
        car: 'Audi'
    }
];

And I want to get one of these objects based on user input. Let's say we want to get the 3rd item's index by Obejct's ID:

let index = group.findIndex(g => g.id === payload.id);

Once I have the index I want to assign new values to this object like this:

group[index].id = payload.id;
group[index].name = payload.name;
group[index].geo = payload.geo;
group[index].car = payload.car;

However it is long, ugly, and imagine if you'd have 50+ values inside this object.

Question: Is there any shorter and more efficient way of achieving the same? Including ES6-ES7 syntaxes also.


Solution

  • You could use Array#find and Object.assign for changing the properties of the found object.

    var group = [{ id: 1, name: 'Test 1', geo: 'Japan', car: 'Toyota' }, { id: 2, name: 'Test 2', geo: 'USA', car: 'Tesla' }, { id: 3, name: 'Test 3', geo: 'Germany', car: 'Audi' }],
        payload = { id: 3, name: 'update', geo: 'Germany Bavaria Ingolstadt', car: 'Audi 1' },
        object = group.find(({ id }) => id === payload.id);
    
    if (object) {
        Object.assign(object, payload);
    }
    
    console.log(group);
    .as-console-wrapper { max-height: 100% !important; top: 0; }