jQuery:显示密钥的名称和Json Array的值

时间:2016-03-02 10:40:54

标签: jquery json

我有一个json数组,如下所示:

var data =[{"id":"1","name1":"avi", "age":"20"},{"id":"2","name1":"suresh","age":"30"}, {"id":"3","name1":"rajesh", "age":"40"}];

我可以检索键值对或按键获取值。但这里第二个地方(name1)的密钥名称不是常数(可以是任何东西)。我所知道的是我应该能够在每个数组的第二个位置获取键的名称并显示其值。这就是我的方式:



var data =[
{"id":"1","name1":"avi", "age":"20"},
{"id":"2","name1":"suresh","age":"30"},
{"id":"3","name1":"rajesh", "age":"40"}
];

var keys = [];
$.each(data, function(key1, value){
  if(key1 == 0){
    $.each(value, function(k,v){
      keys.push(k);
    });
  }
  console.log(keys[1]+ "::"+value[keys[1]]);   
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我可以获得结果

enter image description here

但我认为还有更好,更干净的方法。如果有,请告诉我。

对于每个对象,如何通过执行类似obj [2] .key和obj [2] .value ??

的操作来获取相应的键值对。

5 个答案:

答案 0 :(得分:0)

If you know the keys you can try

for(var i in data)
{
   var name = data[i].name1;
   console.log(name);
}

Else link in comment is best option.

答案 1 :(得分:0)

Do you mean something like this ?

Object keys returns the array of object keys

var key = Object.keys(obj)[0] //This contains the id
obj[key] //This contains the value

Another way without jquery

// Code goes here
var data =[
{"id":"1","name1":"avi", "age":"20"},
{"id":"2","name1":"suresh","age":"30"},
{"id":"3","name1":"rajesh", "age":"40"}
];

//Just to get the logic
for(var el in data){

      var obj = data[el];
      var keys = Object.keys(obj); //Returns array of keys

      for(var i in keys){
        var key = keys[i]

        console.log(key+" "+obj[key]);
      }
}

here is a plunker https://plnkr.co/edit/K4xM1X2xeNSyf3BrBCRs?p=preview

答案 2 :(得分:0)

This will get you the value of object in second location

 $.each(data, function(key1, value){
  if(key1===1)
    var x = data[key1];
  }

答案 3 :(得分:0)

The proprieties of an object doesn't have an order, so you have to change strategy, for example create a key called "name" that contains an array of two values, [name1, avi], where name1 is the dynamic propriety.

var data =[
{"id":"1", "name": ["name1","avi"], "age":"20"},
{"id":"2", "name": ["name2","blabla"],"age":"30"},
{"id":"3", "name": ["name3","hello"], "age":"40"}
];


data.forEach(function(element, index, array){
  document.body.innerHTML += ('the ' + element.name[0] + ' is ' +     element.name[1] + '<br>')
});

答案 4 :(得分:0)

If you want to get the unknown key and you know the others, you could use object keys property (check browser support) and filter it out:

var knownKeys = ['id','age'];
var keyName = Object.keys(data[0]).filter(function(k){return knownKeys.indexOf(k) === -1;}).toString(); // >> name1

-jsFiddle-