[英]Update element in nested array, immutably
I'm trying to update the price of a BMW 730d in the following json. 我正在尝试在以下json中更新BMW 730d的价格。
The cars object should be a new object, (Immutability), so I need to use the map function. cars对象应该是一个新对象(不可变性),因此我需要使用map函数。
And I don't want to use libraries like immutable or normalizr. 而且我不想使用不可变或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. [编辑]我在json中添加了一个ID“品牌”以标识模型。
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: 您将检查当前对象是否与BMW有关,并为其返回一个新对象(具有所需的新模型列表),否则,仅返回未更改的对象:
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. 要更新model
数组中的各个对象,请再次使用完全相同的方法。
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. Object.keys
是我能想到的最好方法。 It returns an array, so you have to key in to the index 0
. 它返回一个数组,因此您必须键入索引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: 您必须测试对象的属性,可以使用对象的“ hasOwnProperty”方法来知道对象x是否具有属性y,在这种情况下,您必须执行以下测试:
If(brand.hasOwnProperty('BMW')) {
// To do
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.