Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

javascript - How to get data from nested objects in the form of array

As you can see, the keys are now the name of the items and the corresponding value is another object consisting of two keys - quantity and price.

    var itemsToBuy = {
    milk: {
        quantity : 5,
        price: 20
    },
    bread: {
        quantity : 2,
        price: 15
    },
    potato: {
        quantity : 3,
        price: 10
    }
}

I tried but I am getting only undefined output. Want to get data such like :

['milk', 'bread', 'potato']

[20, 15, 10]
question from:https://stackoverflow.com/questions/65641648/how-to-get-data-from-nested-objects-in-the-form-of-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solution

  • With Object.keys() you can get the keys of your Object as an array. -> ['milk', 'bread', 'potato']

  • With Object.entries() in combination with map() you can get the values of the price property as an array. -> [20, 15, 10]

Example:

     var itemsToBuy = {
        milk: {
            quantity : 5,
            price: 20
        },
        bread: {
            quantity : 2,
            price: 15
        },
        potato: {
            quantity : 3,
            price: 10
        }
    }
    const keys = Object.keys(itemsToBuy);
    const val = Object.entries(itemsToBuy).map((element)=> element[1].price)

    console.log(keys);
    console.log(val);
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...