0

I have this empty array:

 prices: [
      {
          price:null,
          zone_id: null,
      }
 ]

how can i map my data to this empty array? Example data.

product:[
   0:{
       brand: 'a',
       size: '11',
       price: '120',
       zone_id: '1'
   }
]

How can I push only the price and zone id to that empty prices array

what i have right now.

this.prices.push(product);

the value of prices array should be

prices:[
   {
      price: '120',
      zone_id: '1'
   }
]
Dhenz
  • 13
  • 1
  • 5

1 Answers1

1

If you have an empty array prices:

let prices = [];

and a data array product containing information about each product:

let product = [
   {
       brand: 'a',
       size: '11',
       price: '120',
       zone_id: '1'
   }, 
   {
       brand: 'b',
       size: '19',
       price: '200',
       zone_id: '4'
   }
];

Single Product:

You can push the first product's price and zone_id to the prices array like this (using object destructuring):

prices.push((({price, zone_id}) => ({price, zone_id}))(product[0]));

All Products: If you want to do the same thing for all of the products you can use a forEach loop:

product.forEach(p => {
    prices.push((({price, zone_id}) => ({price, zone_id}))(p));
});

All Products (Replacement):

If you want to do add all products and don't care about the original contents of the prices array (or if you know it will be empty) you can just use a map to apply the same function to each entry of product and store the result in prices:

prices = product.map(({price, zone_id}) => ({price, zone_id}));
Ollin Boer Bohan
  • 2,296
  • 1
  • 8
  • 12
  • hi olln I got this error: Cannot read property 'price' of undefined – Dhenz Jul 10 '18 at 15:17
  • It's likely that you haven't declared the `product` array correctly. In the original post you've written: `product:[ 0:{ brand: 'a', size: '11', price: '120', zone_id: '1' } ]` But that isn't valid. To store something in a variable you need to use `=` and `let`/`const`/`var`, like: `let product = ...` And you can't use "key:value" for the items in an array (no `0:...`). Try: `let product = [ { brand: 'a', size: '11', price: '120', zone_id: '1' } ]` – Ollin Boer Bohan Jul 10 '18 at 15:21