0

我正在使用一个 API,并且我将它对成功函数的响应作为数据获得。

我正在尝试使用它只给我所有对象的“键”而不是值,所以我的问题是:我可以使用以下方法获取值吗?

我已经使用 JavaScript 的object.key()方法获得了所有对象的“键”,但现在我也想获得它们的值。

这是回应。我在控制台中获取了一个回复片段。

division: Object
active: 1
country: "United States"
lat: 42.3584647
lon: -71.05962
name: "Boston"
url: "http://yipit.com/boston/"

下面是为获取对象的键而编写的函数:

function getvalues(data){
    for(var i = 0;i <= data.response.deals.length-1; i++){
        var obj = [];
        var num = i + 1;
        var keyArray = Object.keys(data.response.deals[i].division);
        $('#empid h6').html(keyArray);
        //here i get the keys of objects which is country,lat,lon etc.
        console.log("value of keyArray "+num+" is "+keyArray);
    }    
}
4

3 回答 3

0

尝试

function getvalues(data){
    $.each(data.response.deals, function(i, deal){
        var keys = [], values = [];
        $.each(deal, function(key, value){
            keys.push(key);
            values.push(value);
        });

        console.log('keys ' + (i + 1) + ' is ' + keys);
        console.log('values ' + (i + 1) + ' is ' + values);
    });
}
于 2013-05-14T12:54:06.187 回答
0

Underscore 库有各种很好的帮助器来实现功能,还有一个#values()帮助器:

> myObj= { 师:'师',
  名称:“波士顿”,
  网址:'http://yipit.com/boston/'}

> _.values(myObj);
[ '分配',
  “波士顿”,
  'http://yipit.com/boston/' ]
于 2013-05-14T13:03:59.917 回答
-1

This will display all the values associated with the keys :

var myObject = data.response.deals[i].division;
    for (var key in myObject ) {
      if (myObject.hasOwnProperty(key)) {
        alert(key + " is " + myObject[key]);
        alert(key + " is " + myObject.key);
      }
    }

To call a "key" on a an object (which is actually a function or property) you can do either myObject[key], or myObject.key

于 2013-05-14T12:34:56.233 回答