JSON响应在Javascript中解析以获取键/值对 [英] JSON response parsing in Javascript to get key/value pair

查看:108
本文介绍了JSON响应在Javascript中解析以获取键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我有一个嵌套数据结构/如何访问特定值?

如何才能在Javascript中获取每个对象的名称和值?

How can I get the name and value of each object in Javascript only?

推荐答案

有两种方法可以访问对象的属性:

There are two ways to access properties of objects:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

或者,如果您需要动态执行此操作:

Or, if you need to dynamically do it:

var key = 'b';
obj[key] //bar

如果您还没有对象,您需要转换它

If you don't already have it as an object, you'll need to convert it.

对于更复杂的示例,我们假设您有一组代表用户的对象:

For a more complex example, let's assume you have an array of objects that represent users:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

要访问第二个用户的年龄属性,您将使用用户[ 1]。年龄。要访问第一个用户的第二个favoriteFood,您将使用 users [0] .favoriteFoods [2]

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

另一个例子: obj [2] .key [3] [some key]

这将访问名为2的数组的第3个元素。然后,它将访问该数组中的key,转到该数组的第三个元素,然后访问属性名称某个键

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.

正如Amadan所说,可能还值得讨论如何循环不同的结构。

As Amadan noted, it might be worth also discussing how to loop over different structures.

要循环数组,可以使用简单的for循环:

To loop over an array, you can use a simple for loop:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

循环一个对象有点复杂。如果你绝对肯定对象是普通对象,你可以使用普通的来代替(x in obj){} 循环,但它更安全一些添加 hasOwnProperty 检查。在无法验证对象没有继承属性的情况下,这是必需的。 (它还将来会证明代码。)

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(请注意,我假设任何JS实现你'使用has console.log 。如果没有,你可以使用 alert 或者某种DOM操作。)

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

这篇关于JSON响应在Javascript中解析以获取键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆