Accessing elements of JSON object without knowing the key names

后端 未结 5 1190
礼貌的吻别
礼貌的吻别 2020-11-30 10:00

Here\'s my json:

{\"d\":{\"key1\":\"value1\",
      \"key2\":\"value2\"}}

Is there any way of accessing the keys and values (in javascript)

相关标签:
5条回答
  • 2020-11-30 10:02

    By using word "b", You are still using key name.

    var info = {
    "fname": "Bhaumik",
    "lname": "Mehta",
    "Age": "34",
    "favcolor": {"color1":"Gray", "color2":"Black", "color3":"Blue"}
    };
    

    Look at the below snippet.

    for(key in info) {
      var infoJSON = info[key];
      console.log(infoJSON);
    }
    

    Result would be,

    Bhaumik
    Mehta
    Object {color1: "Gray", color2: "Black", color3: "Blue"} 
    

    Don’t want that last line to show up? Try following code:

    for(key in info) {
      var infoJSON = info[key];
        if(typeof infoJSON !== "object"){
           console.log(infoJSON);
      }
    }
    

    This will eliminate Object {color1: “Gray”, color2: “Black”, color3: “Blue”} from showing up in the console.

    Now we need to iterate through the variable infoJSON to get array value. Look at the following whole peace of code.

    for(key in info) {
        var infoJSON = info[key];
        if (typeof infoJSON !== "object"){
           console.log(infoJSON);
        }
     }
    
    for(key1 in infoJSON) {
        if (infoJSON.hasOwnProperty(key1)) {
           if(infoJSON[key1] instanceof Array) {
              for(var i=0;i<infoJSON[key1].length;i++) {
                 console.log(infoJSON[key1][i]);
              }
            } else {console.log(infoJSON[key1]);}
        }
     }
    

    And now we got the result as

    Bhaumik
    Mehta
    Gray
    Black
    Blue
    

    If we use key name or id then it’s very easy to get the values from the JSON object but here we are getting our values without using key name or id.

    0 讨论(0)
  • 2020-11-30 10:19
    {
      "d":{
         "key1":"value1",
         "key2":"value2"
        }
    }
    

    To access first key write:

       let firstKey=Object.keys(d)[0];
    

    To access value of first key write:

    let firstValue= d[firstKey];
    
    0 讨论(0)
  • 2020-11-30 10:20

    Use for loop to achieve the same.

    var dlist = { country: [ 'ENGLAND' ], name: [ 'CROSBY' ] }
    
    for(var key in dlist){
         var keyjson = dlist[key];
         console.log(keyjson)
       }

    0 讨论(0)
  • 2020-11-30 10:22

    Is this what you're looking for?

    var data;
    for (var key in data) {
       var value = data[key];
       alert(key + ", " + value);
    }
    
    0 讨论(0)
  • 2020-11-30 10:28

    You can use the for..in construct to iterate through arbitrary properties of your object:

    for (var key in obj.d) {
        console.log("Key: " + key);
        console.log("Value: " + obj.d[key]);
    }
    
    0 讨论(0)
提交回复
热议问题