简体   繁体   中英

Retrieve object from json object

I'm getting a JSON object from my database that looking like this :

products = [
    {"ID":1, "CODE":"code1", "DESCRIPTION":"abcd", "PRICE":100},
    {"ID":2, "CODE":"code2", "DESCRIPTION":"efgh", "PRICE":100},
    {"ID":3, "CODE":"code3", "DESCRIPTION":"ijkl", "PRICE":100}
];

Then I have a select element with options having text = CODE and value = ID for each product. Now when user select a product in the dropdown, I want to fill some textboxes with DESCRIPTION and PRICE of the selected product. Is there any built-in function to do something like this :

var myObject = products("ID" = selectedValue)

?

I'd like to use

myObject.DESCRIPTION, myObject.PRICE

to fill my textboxes. Thank you

You can use $.each utility function:

$('select').change(function(){
   var id = this.value;
   $.each(products, function(i, myObject){
      if (myObject.ID === id) {
        $('textarea').val(myObject.DESCRIPTION);
        return false;
      }
   })
})

Modern javascript engines (IE9 and above, node.js and standards compliant browsers) also support the functional list methods for arrays: map , reduce , and filter .

This is a classic case for filter :

var myObject = products.filter(function(x){return x.ID == selectedValue})[0];

For older borwsers you can implement this shim:

if (!Array.prototype.filter) {
    Array.prototype.filter = function(callback, myself) {
        if (!myself) myself = this;
        var result = [];
        for (var i=0;i<myself.length;i++) {
            if (callback(myself[i],i,myself)) result.push(myself[i]);
        }
        return result;
    }
}

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