const myJSON = {
seller1: [
{
product: "headphones",
price: 23,
weight: 1
},
{
product: "earphone",
price: 12,
weight: 1
},
{
product: "iPhone",
price: 999,
weight: 3
},
{
product: "ipad",
price: 399,
weight: 4
}
],
seller2: [
{
product: "headphones",
price: 25,
weight: 1
},
{
product: "earphone",
price: 10,
weight: 1
},
{
product: "iPhone",
price: 949,
weight: 2
},
{
product: "ipad",
price: 449,
weight: 3
}
]
}
var myFilteredProducts = {}
selectedOptions.map(selectedOption => {
for ( const [ key, value ] of Object.entries(myJSON) ) {
const filteredProducts = _.find(value, selectedOption)
console.log(selectedOption)
myFilteredProducts[key] = filteredProducts
}}
)
对于我的上述代码,何时
selectedOptions = [{product: "iphone"}]
console.log(myFilteredProducts)
// {
// seller1: [
// {
// product: "iPhone",
// price: 999,
// weight: 3
// }
// ],
// seller2: [
// {
// product: "iPhone",
// price: 949,
// weight: 2
// }
// ]
// }
何时
selectedOptions = [{product: "iphone"}, {product: "headphones"}]
console.log(myFilteredProducts)
而不是结果,
// {
// seller1: [
// {
// product: "headphones",
// price: 23,
// weight: 1
// },
// {
// product: "iPhone",
// price: 999,
// weight: 3
// }
// ],
// seller2: [
// {
// product: "headphones",
// price: 25,
// weight: 1
// },
// {
// product: "iPhone",
// price: 949,
// weight: 2
// }
// ]
// }
我正在
// {
// seller1: [
// {
// product: "headphones",
// price: 23,
// weight: 1
// }
// ],
// seller2: [
// {
// product: "headphones",
// price: 25,
// weight: 1
// }
// ]
// }
我做错了什么?
答案 0 :(得分:0)
const sellers = Object.entries(myJSON), result = {}, options = selectedOptions.map(option => option.product);
for(const [seller, products] of sellers){
const filtered = products.filter(product => options.includes( product.product ));
if(filtered.length) result[seller] = filtered;
}