如果我不知道名称,如何访问 javascript 对象的属性? [英] How do I access properties of a javascript object if I don't know the names?

查看:29
本文介绍了如果我不知道名称,如何访问 javascript 对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个这样的 javascript 对象:

Say you have a javascript object like this:

var data = { foo: 'bar', baz: 'quux' };

您可以通过属性名称访问属性:

You can access the properties by the property name:

var foo = data.foo;
var baz = data["baz"];

但是如果您不知道属性的名称,是否可以获得这些值?这些属性的无序性质是否使得无法区分它们?

But is it possible to get these values if you don't know the name of the properties? Does the unordered nature of these properties make it impossible to tell them apart?

在我的例子中,我特别考虑了一个函数需要接受一系列名称-值对的情况,但属性的名称可能会改变.

In my case I'm thinking specifically of a situation where a function needs to accept a series of name-value pairs, but the names of the properties may change.

到目前为止,我对如何做到这一点的想法是将属性的名称与数据一起传递给函数,但这感觉就像一个黑客.如果可能的话,我更愿意通过内省来做到这一点.

My thoughts on how to do this so far is to pass the names of the properties to the function along with the data, but this feels like a hack. I would prefer to do this with introspection if possible.

推荐答案

旧版本的 JavaScript (< ES5) 需要使用 for..in 循环:

Old versions of JavaScript (< ES5) require using a for..in loop:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    // do something with key
  }
}

ES5 引入了 Object.keysArray#forEach 这让这更容易一些:

ES5 introduces Object.keys and Array#forEach which makes this a little easier:

var data = { foo: 'bar', baz: 'quux' };

Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
  // do something with data[key]
});

ES2017 引入了 Object.valuesObject.entries.

Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]

这篇关于如果我不知道名称,如何访问 javascript 对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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