2

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"
       },   
]
3
  • 1
    The snippet above is not a valid JS code. Assuming, that detail is an array of objects, you can get result by having let result = detail.map(item => ({Price: item.Price})) Commented May 27, 2021 at 10:30
  • 1
    You can use the answers shown here: how to map more than one property from array of object in javascript Commented May 27, 2021 at 10:31
  • Yes, you are right but I didn't look at the map function before now it working with the map function. Thank you @EugeneKarataev Commented May 27, 2021 at 11:01

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

One more problem I am having, what if the Price is a array of object. How to access that key value? @RanTurner
0

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

Comments

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.