简体   繁体   中英

Update element in nested array, immutably

I'm trying to update the price of a BMW 730d in the following json.

The cars object should be a new object, (Immutability), so I need to use the map function.

And I don't want to use libraries like immutable or normalizr. The aim is to get my head around the map function, but I'm stuck evaluating the brand name.

const cars =
[
    {
        brand: 'BMW',
        model: [
            {
                name: '535d',
                price: 35000
            }, {
                name: '730d',
                price: 55000
            }
        ]
    },
    {
        brand: 'Mercedes',
        model: [
            {
                name: 'roadstar',
                price: 75000
            },
        ]
    },
];

This is what I have so far :

// trying to update the price of a BMW 730d

const newCars= cars.map(brand => {
    console.log(brand);
    // and now ?

});

But now I'm stuck.

Who helps me out?

Thanks!

[EDIT] I added an id "brand" in the json to identify the models.

You would check whether the current object concerns the BMWs and return a new object (with the desired new model list) for it, or just return the unchanged object otherwise:

const newCars = cars.map(car => {
    if (car.brand == "BMW") {
        return {
            brand: "BMW",
            model: car.model.map(model => {
                // …
            }),
        };
    } else {
        return car;
    }
});

For updating the respective object in the model array, use exactly the same approach again.

As a technicality, your phrasing of immutability is incorrect. Immutable means a fundamental inability to mutate. In your case, you're simply making the decision to not mutate.

Unfortunately, based on the structure of your data, you have to get a little messy to extract the key. Object.keys is the best way I can think of. It returns an array, so you have to key in to the index 0 .

cars.map(car => {
  const brand = Object.keys(car)[0];
  if (brand === 'BMW') {
  }
})

You have to test on the object's property, you can use the method "hasOwnProperty" of an object to know if an object x has a property y or not, in your case you have To do the following test:

If(brand.hasOwnProperty('BMW')) {
  // To do 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM