从 JavaScript 中的对象获取值 [英] Get values from an object in JavaScript

查看:30
本文介绍了从 JavaScript 中的对象获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个对象:

var data = {"id": 1, "second": "abcd"};

这些是来自表单的值.我正在将其传递给一个函数进行验证.

These are values from a form. I am passing this to a function for verification.

如果上述属性存在,我们可以通过 data["id"]data["second"] 获取它们的值,但有时,基于其他值,属性可以不同.

If the above properties exist we can get their values with data["id"] and data["second"], but sometimes, based on other values, the properties can be different.

如何从 data 中获取独立于属性名称的值?

How can I get values from data independent of property names?

推荐答案

要访问对象的属性而不知道这些属性的名称,您可以使用 for ... in 循环:

To access the properties of an object without knowing the names of those properties you can use a for ... in loop:

for(key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
        //do something with value;
    }
}

这篇关于从 JavaScript 中的对象获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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