简体   繁体   中英

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

For my above code, when

selectedOptions = [{product: "iphone"}]
console.log(myFilteredProducts)
// {
//   seller1: [
//     {
//       product: "iPhone",
//       price: 999,
//       weight: 3
//     }
//   ],
//   seller2: [
//     {
//       product: "iPhone",
//       price: 949,
//       weight: 2
//     }
//   ]
// }

When

selectedOptions = [{product: "iphone"}, {product: "headphones"}]
console.log(myFilteredProducts)

instead of the result being,

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

I am getting

// {
//   seller1: [
//     {
//       product: "headphones",
//       price: 23,
//       weight: 1
//     }
//   ],
//   seller2: [
//     {
//       product: "headphones",
//       price: 25,
//       weight: 1
//     }
//   ]
// }

What am I doing wrong?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM