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'
   }
]
2
  • You mean like this: this.prices.push({price:product[0].price,zone_id:product[0].zone_id}); Commented Jul 10, 2018 at 15:11
  • Cannot read property 'price' of undefined got that error, but yes something like that Commented Jul 10, 2018 at 15:13

1 Answer 1

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}));
Sign up to request clarification or add additional context in comments.

2 Comments

hi olln I got this error: Cannot read property 'price' of undefined
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' } ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.