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

查看:147
本文介绍了如果我不知道名字,我该如何访问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 loop:

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.keys Array#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.values Object.entries

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

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

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