簡體   English   中英

將對象推入對象數組

[英]Push object into array of objects

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
//     }
//   ]
// }

我究竟做錯了什么?

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM