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

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

问题描述

如何仅在 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']}];

要访问第二个用户的年龄属性,您可以使用 users[1].age.要访问第一个用户的第二个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 的数组的第三个元素.然后,它将访问该数组中的key",转到该数组的第三个元素,然后访问属性名称 some 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]);
}

循环对象有点复杂.如果您绝对肯定对象是普通对象,则可以使用普通的 for (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 实现都有 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.)

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

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