简体   繁体   中英

Destructuring object properties from an array of objects and rendering those properties into an array

I currently have two objects (it's a lot but this is what I want to draw your attention to.) As you can see, this is an array of objects. What I want to do is to pull out specified properties of each object and store that in an array. So for example I would want object property Price , I'd like to get each Price property of the object and store all of it in an array that would only contain it's value like in this case: [215.23,215.23]

 [{
        CompanyName: "Microsoft Corp.",
        Date: 1606503905,
        Price: 215.23,
        Quantity: 50,
        Symbol: "MSFT",
        TotalCost: 10761.5
      },
      {
        CompanyName: "Microsoft Corp.",
        Date: 1606503913,
        Price: 215.23,
        Quantity: 25,
        Symbol: "MSFT",
        TotalCost: 5380.75
      }
    ]

Here's a snippet:

function RadialChart(props) {
    const { transactionData } = props; //Array of objects stored here
    transactionData.map((data) => {console.log(data.TotalCost)})

I tried using useState and the map method but I don't think I was doing it right. When I was using map, I declared a const arr= [] then did an arr.concat(data.TotalCost) and that didn't work. Please let me know if you guys have a solution. Thank you.

If you want just an array of prices, then just map it and return the price:

const prices = transactionData.map((data) => data.Price);
console.log(prices); // [215.23, 215.23]

You can get what you want simply with map.

 const myArray = [{ CompanyName: "Microsoft Corp.", Date: 1606503905, Price: 215.23, Quantity: 50, Symbol: "MSFT", TotalCost: 10761.5, }, { CompanyName: "Microsoft Corp.", Date: 1606503913, Price: 215.23, Quantity: 25, Symbol: "MSFT", TotalCost: 5380.75, } ] console.log('CompanyName', myArray.map(x => x.CompanyName)) console.log('Date', myArray.map(x => x.Date)) console.log('Price', myArray.map(x => x.Price)) console.log('TotalCost', myArray.map(x => x.TotalCost))

If you want to set it to state...

declare useState

const [ price, setPrice ] = useState([]);

setPrice

setPrice(myArray.map( x => x.Price ))

Use destructuring and map to get the prices. (Just adding destructuring to @Aplet123's suggestion)

 const data = [ { CompanyName: "Microsoft Corp.", Date: 1606503905, Price: 215.23, Quantity: 50, Symbol: "MSFT", TotalCost: 10761.5, }, { CompanyName: "Microsoft Corp.", Date: 1606503913, Price: 123.23, Quantity: 25, Symbol: "MSFT", TotalCost: 5380.75, }, ]; const prices = data.map(({ Price }) => Price); console.log(prices);

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