How to fetch particular data from array of objects and store in new array in js (vue js)

Viewed 601

I am having this array of object

let detail : [ 
       0: {
            Code: "Code 1"
            Price: "0.00"   
          },           

       1: {
            Code: "Code 2"
            Price: "9.00"   
          }
]

I want to store the price in an array(for eg: result) so that I can merge it with another existing array of the object(for eg: alldetail)

result = [
    0: {
          Price:"0.00"
       },
    1: {
          Price:"9.00"
       },   
]
2 Answers

Using map() method which creates a new array filled with the results of the provided function executing on every element in the calling array.

So, in your case, you'll return an object with the key Price and the value will be the current object with the value of it's Price property.

let detail = [ 
        {
            Code: "Code 1",
            Price: "0.00"   
          },           

       {
            Code: "Code 2",
            Price: "9.00"   
          }
];

let result = detail.map(current => {return {Price: current.Price}});

console.log(result);

Use map to create a new array of objects.

const detail = [ 
  { Code: "Code 1", Price: "0.00" },           
  { Code: "Code 2", Price: "9.00" }
];

const result = detail.map(({ Price }) => ({ Price }));

console.log(result);

Additional documentation

Related