0

In the following code I want to replace the {cash} with a variable so that I can return any of the data items from the JSON. Any idea how to do this?

Javascript:

    let chartLabels = arr.map(({date}) => date).reverse();
    let chartData = arr.map(({cash}) => cash).reverse();

JSON:

    0: "{\"date\":\"2020-03-31\"\"totalAssets\":\"300280000000.00\",\"intangibleAssets\":null,\"earningAssets\":null,\"otherCurrentAssets\":\"5598000000.00\",\"totalLiab\":\"229507000000.00\",\"totalStockholderEquity\":\"58431000000.00\",\"deferredLongTermLiab\":\"734000000.00\",\"otherCurrentLiab\":\"50891000000.00\",\"commonStock\":\"12267000000.00\",\"cash\":\"20305000000.00}"
    1: "{\"date\":\"2019-12-31\",\"totalAssets\":\"306928000000.00\",\"intangibleAssets\":\"482000000.00\",\"earningAssets\":null,\"otherCurrentAssets\":null,\"totalLiab\":\"229599000000.00\",\"totalStockholderEquity\":\"64106000000.00\",\"deferredLongTermLiab\":\"652000000.00\",\"otherCurrentLiab\":\"4531000000.00\",\"commonStock\":\"12267000000.00\",\"cash\":\"25567000000.00}"
    2: "{\"date\":\"2019-09-30\","totalAssets\":\"301016000000.00\",\"intangibleAssets\":\"3652000000.00\",\"earningAssets\":null,\"otherCurrentAssets\":\"7666000000.00\",\"totalLiab\":\"222408000000.00\",\"totalStockholderEquity\":\"65315000000.00\",\"deferredLongTermLiab\":\"558000000.00\",\"otherCurrentLiab\":\"15735000000.00\",\"commonStock\":\"12267000000.00\",\"cash\":\"26994000000.00}"
3
  • 2
    what is your expected result? Commented Aug 4, 2020 at 11:38
  • 1
    Can you please elaborate? from what I understood, that's pretty simple, take a variable and assign any property value from the JSON. and pass the variable into map. Correct me if I'm missing something. Commented Aug 4, 2020 at 11:39
  • You can use destructuring like so: .map(({[variable]: val}) => val) Commented Aug 4, 2020 at 11:54

1 Answer 1

3

By writing ({cash}) => cash you are destructuring the cash from the object. To access a variable property you can take the whole object and access the property dynamicaly:

var variable = 'cash';
arr.map(data => data[variable]).reverse();
Sign up to request clarification or add additional context in comments.

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.