从 JavaScript 中的对象获取值

我有个目标:

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

这些是来自表单的值,我将它传递给一个函数进行验证。

如果存在上述属性,我们可以用 data["id"]data["second"]得到它们的值,但有时,基于其他值,这些属性可能会不同。

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

493602 次浏览

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;
}
}

I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array

To access the attributes of an object is pretty easy:

alert(data.second);

But, if this does not completely answer your question, please clarify it and post back.

Thanks !

If you want to do this in a single line, try:

Object.keys(a).map(function(key){return a[key]})

If you $ is defined then You can iterate

var data={"id" : 1, "second" : "abcd"};
$.each(data, function() {
var key = Object.keys(this)[0];
var value = this[key];
//do something with value;
});

You can access it by following way If you know the values of keys

data.id

or

data["id"]

In ES2017 you can use Object.values():

Object.values(data)

At the time of writing support is limited (FireFox and Chrome).All major browsers except IE support this now.

In ES2015 you can use this:

Object.keys(data).map(k => data[k])

Using lodash _.values(object)

_.values({"id": 1, "second": "abcd"})


[ 1, 'abcd' ]

lodash includes a whole bunch of other functions to work with arrays, objects, collections, strings, and more that you wish were built into JavaScript (and actually seem to slowly be making their way into the language).