[英]How to add property value from one array of objects into another (for the matching objects) in JS
I am trying to filter array of objects based on another array of objects and after finding all matching items I want to set property and value from the first array object into corresponding object in the second array:我正在尝试根据另一个对象数组过滤对象数组,在找到所有匹配项后,我想将第一个数组 object 中的属性和值设置为第二个数组中相应的 object:
const searchedProducts = products.filter(product =>
uniqueProducts.some(
uniqueProduct =>
product.productId === uniqueProduct.productId,
),
)
After here I need to set product.productName for each unique product object under productName property.在这里之后,我需要为 productName 属性下的每个唯一产品 object 设置 product.productName。
Ho such a thing can be achieved in a better way?何以更好的方式实现这样的事情?
This is probably most straightforward using reduce()
combined with find()
to both retrieve and verify that the second array contains each object.这可能是最直接的使用
reduce()
结合find()
来检索和验证第二个数组是否包含每个 object。
const uniqueProducts = [ {id: 3, from: 'uniqueProducts', name: 'Unique 1'}, {id: 12, from: 'uniqueProducts', name: 'Unique 12'} ]; const products = [ {id: 1, from: 'products', name: 'Product 1'}, {id: 2, from: 'products', name: 'Product 2'}, {id: 9, from: 'products', name: 'Product 9'}, {id: 12, from: 'products', name: 'Product 12'}, ]; const output = products.reduce((a, p) => { const uP = uniqueProducts.find(u => u.id === p.id); if (uP) a.push({...p, name: uP.name}); return a; }, []); console.log(output);
I have inventory where I have to add a price property and take its value from products array so I did this,我有库存,我必须在其中添加一个价格属性并从产品数组中获取它的值,所以我这样做了,
inventory = [
{
"productId": 1,
"quantity": 100,
"name": "2 Yolks Noodles",
"image": "twoeggnoodles.jpg",
}
]
Products = [
{
"id": 1,
"quantity": 100,
"name": "2 Yolks Noodles",
"image": "twoeggnoodles.jpg",
"price": 34.95
}
]
let product:any = [];
products.map((prod:any)=>{
const index:any = inventory.find((u:any) => u.productId === prod.id);
// console.log("item", index, '-', prod)
if(index){
product.push({...index, price: prod.price});
}
return prod
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.