我有一个主数组:
const purchaseData = [
{
product_id: "product_id_1",
localized_title: "Product Title 1",
... other attributes
},
{
product_id: "product_id_2",
localized_title: "Product Title 2",
... other attributes
},
我希望用一个数组替换localized_title,该数组包含某些产品ID的更新后的localized_title。
例如:
updatedData = [
{
product_id: "product_id_1",
localized_title: "Updated Product Title 1",
...other random attributes // different from the attributes in the objects of purchaseData
},
];
在这种情况下,purchaseData的第一个子元素只应更新其localized_title。是否有一种优雅的方法可以在不使用for循环和更改数据的情况下完成此操作?我尝试了许多方法,但似乎代码行数太多(不够简洁)。
这是我尝试过的内容:
const updatedData = purchaseData.map(obj => {
const foundObject = originalProducts.find(
o => o.product_id === obj.product_id,
);
const localized_title = foundObject && foundObject.localized_title
if (localized_title) {
return {...obj, localized_title}
}
return obj;
});
map()
或reduce()
。 - norbitrial