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
233 views
in Technique[技术] by (71.8m points)

javascript - How to find value in JSON object array?

I have a JSON object like this

myObj = {
"knowncount": [{
    "id": "planet",
    "knownCount": 8,
    "updateDate": "24/08/2006",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/planet"
}, {
    "id": "dwarfPlanet",
    "knownCount": 5,
    "updateDate": "24/08/2006",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/dwarfPlanet"
}, {
    "id": "asteroid",
    "knownCount": 1027022,
    "updateDate": "11/11/2020",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/asteroid"
}, {
    "id": "comet",
    "knownCount": 3690,
    "updateDate": "11/11/2020",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/comet"
}]}

How can I search my object to find where the key is 'id' and then print its value for knownCount?

Example. If 'id' == 'planet'

// 8

I've tried to covert to array to use array functions like array.find() but this doesn't seem to work. I check type with typeof and continue to get type object. What is the correct way to change to array or is there a comparable way to do this with objects or must I iterate over the object and create a set or something similar?

question from:https://stackoverflow.com/questions/65909370/how-to-find-value-in-json-object-array

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

1 Answer

0 votes
by (71.8m points)
myObj
 .knowncount
 .find(({ id }) => id === 'planet')
 .knownCount;

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

...