So I have this main array:
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
},
And I'd like to replace the localized_title with an array that contains some updated localized_title for certain product_ids
example:
updatedData = [
{
product_id: "product_id_1",
localized_title: "Updated Product Title 1",
...other random attributes // different from the attributes in the objects of purchaseData
},
];
In this case, the purchaseData's first child only should have its localized_title updated. Is there an elegant way of doing this without using For...lopps and without mutating the data? I've tried many ways but I seem to write too many lines of code (not very clean).
This is what I tried:
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;
});
I'd use a Map to simplify retrieving the objects(this also makes the code O(n)):
const productById = new Map(products.map(it => ([it.product_id, it])));
const updated = purchases.map(purchase => {
const product = productById.get(purchase.product_id);
if (product && product.localized_title) {
return { ...purchase, localized_title: product.localized_title, };
}
return purchase;
});
It will be worth it to optimize your lookup using a Map
to reduce the search for foundObject
from O(n) to O(1), and instead of having two return
statements, you could combine them into one:
const originalProductsMap = new Map(
originalProducts.map(o => [o.product_id, o])
);
const updatedData = purchaseData.map(oldData => {
const newData = originalProductsMap.get(oldData.product_id);
const localized_title = newData && newData.localized_title;
return localized_title
? { ...oldData, localized_title }
: oldData;
});
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.