根据另一个数组的值替换一个数组的值
Replacing values of an array based on values from another array
我有以下数组类型
export const images = [
{ id: "000012", label: "night sky", cost: "35" },
{ id: "000013", label: "country road", cost: "16" },
{ id: "000014", label: "baseball game", cost: "12" },
{ id: "000015", label: "horse racing", cost: "24" },
{ id: "000016", label: "bike gathering", cost: "18" },
...
{ id: "001138", label: "kite surfing", cost: "25" },
还有下面的第二个数组
const product = [
{ product: "000013" },
{ product: "000016" },
...
]
并且我想用我的第一个数组的标签值替换我的产品数组的值。第二个数组保存产品属性中第一个数组的id值。
预期结果为:
const product = [
{ product: "country road" },
{ product: "bike gathering" },
]
这里我运行循环遍历每个product
然后为它找到对应的image
。最后用 image label
.
更新了 product
值
const images = [
{ id: "000012", label: "night sky", cost: "35" },
{ id: "000013", label: "country road", cost: "16" },
{ id: "000014", label: "baseball game", cost: "12" },
{ id: "000015", label: "horse racing", cost: "24" },
{ id: "000016", label: "bike gathering", cost: "18" },
{ id: "001138", label: "kite surfing", cost: "25" },
]
const products = [
{ product: "000012" },
{ product: "000013" },
{ product: "000014" },
]
products.forEach((p, index) => {
const image = images.find(({id}) => id === p.product);
if(image) {
const newVal = {product: image.label};
products[index] = {...p, ...newVal};
}
})
console.log(products)
我有以下数组类型
export const images = [
{ id: "000012", label: "night sky", cost: "35" },
{ id: "000013", label: "country road", cost: "16" },
{ id: "000014", label: "baseball game", cost: "12" },
{ id: "000015", label: "horse racing", cost: "24" },
{ id: "000016", label: "bike gathering", cost: "18" },
...
{ id: "001138", label: "kite surfing", cost: "25" },
还有下面的第二个数组
const product = [
{ product: "000013" },
{ product: "000016" },
...
]
并且我想用我的第一个数组的标签值替换我的产品数组的值。第二个数组保存产品属性中第一个数组的id值。 预期结果为:
const product = [
{ product: "country road" },
{ product: "bike gathering" },
]
这里我运行循环遍历每个product
然后为它找到对应的image
。最后用 image label
.
product
值
const images = [
{ id: "000012", label: "night sky", cost: "35" },
{ id: "000013", label: "country road", cost: "16" },
{ id: "000014", label: "baseball game", cost: "12" },
{ id: "000015", label: "horse racing", cost: "24" },
{ id: "000016", label: "bike gathering", cost: "18" },
{ id: "001138", label: "kite surfing", cost: "25" },
]
const products = [
{ product: "000012" },
{ product: "000013" },
{ product: "000014" },
]
products.forEach((p, index) => {
const image = images.find(({id}) => id === p.product);
if(image) {
const newVal = {product: image.label};
products[index] = {...p, ...newVal};
}
})
console.log(products)