简体   繁体   中英

How can I get specific json data value via the key value

let us say I have the following json in my local storage

top: [ {"id","one","name":"java"},
       {"id","two","name","javascript"},
       {"id","three","name","jquery"]
     ]

The problem here is how can i get the id just by using the name value? For instance, if I want get the id value "two" , I need to be able to make the query using "javascript" then reach the value "two" . Is there a way to achieve the above described problem?

Let's convert your input to object then access it as property

 var input = [{ "id":"one", "name":"java" }, { "id":"two", "name":"javascript" }, { "id":"three", "name":"jquery" }]; var result = input.reduce((acc, b) => { acc[b.name] = b.id; return acc; }, {}); console.log(result['javascript']); 

try with Array#find .your json is invalid .you could change format like this below

 var toper = [{ "id": "one", "name": "java", }, { "id": "two", "name": "javascript", }, { "id": "three", "name": "jquery", } ] function find_id(str) { return toper.find((a) => { if (a.name == str.trim()) { return a } }).id } console.log(find_id('javascript')) 

Your JSON has some typo mistakes. It should be like Tai's example above.

To retrieve it from the local storage (as text) and use it (as json object):

var myJson = JSON.parse(myText)

Then:

for (var i=0 ; i<myJson.length ; i++) {
    if myJson[i].name == "javascript" {
        var a = myJson[i].id;
        console.log(a);
    }
}

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