使用带有嵌套 Javascript 对象的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8750362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:28:21  来源:igfitidea点击:

Using variables with nested Javascript object

javascript

提问by Ben Flynn

Suppose I have this:

假设我有这个:

var a = { A : { AA : 1 }, B : 2 };

Is there a way for me to create a variable that could allow me to reference either AA or B? What would the syntax look like?

有没有办法让我创建一个可以让我引用 AA 或 B 的变量?语法会是什么样的?

// I know I can do this:    
a['B']; // 2
a['A']['AA']; // 1

// something like this?
var myRef = ???;
a[myRef]; 1 or 2 depending on myRef

If not, what's a better way to get what I'm going for here?

如果没有,有什么更好的方法来获得我想要的东西?

回答by Krizz

Not directly.

不直接。

Solution 1 - use object flattening

解决方案 1 - 使用对象展平

Flatten object, to have new object var a = { 'A.AA' : 1; B : 2 };.

展平对象,以拥有新对象var a = { 'A.AA' : 1; B : 2 };

See compressing object hierarchies in JavaScriptor Flattening a complex json object for mvc bindingto get the javascript function for it.

请参阅在 JavaScript 中压缩对象层次结构为 mvc 绑定扁平化复杂的 json 对象以获取其 javascript 函数。

Soution 2 - write key-path accessor

解决方案 2 - 编写密钥路径访问器

I can see it was already addressed by Eugen. Reposted code-reviewed version:

我可以看到 Eugen 已经解决了这个问题。重新发布的代码版本:

function Leaf(obj,path) {
  path=path.split('.');
  var res=obj;
  for (var i=0;i<path.length;i++) res=res[path[i]];
  return res;
}

Solution 3 - use eval

解决方案 3 - 使用 eval

var x = eval("a." + myRef); // x will be 1 for myRef == "A.AA", 2 for "B"

Be careful with this solution as you may introduce some security issues. It is more of the curiosity.

小心使用此解决方案,因为您可能会引入一些安全问题。更多的是好奇心。

回答by Maximiliano Cespedes

Since i also encounter this problem, i wrote also a one line util for this (ES6):

由于我也遇到了这个问题,我也为此写了一个单行工具(ES6):

const leaf = (obj, path) => (path.split('.').reduce((value,el) => value[el], obj))

Example:

例子:

const objSample = { owner: { name: 'Neo' } };
const pathSample = 'owner.name';

leaf(objSample, pathSample) //'Neo'

回答by Eugen Rieck

function Leaf(obj,path) {
  path=path.split('.');
  var res=obj;
  for (var i=0;i<path.length;i++) obj=obj[path[i]];
  return res;
}

Leaf(a,'B')=2

叶(a,'B')=2

Leaf(a,'A.AA')=1

叶(a,'A.AA')=1

Decorate with error handling etc. according to your needs.

根据您的需要使用错误处理等进行装饰。

回答by andy petrella

Actually no, because js object are seen as property bags and doing a[X]is for accessing first level properties only...

实际上不是,因为 js 对象被视为属性包,并且a[X]仅用于访问第一级属性......

But you could wrap the logic a['A']['AA']; // 1in a function that does the same, like this

但是您可以将逻辑包装 a['A']['AA']; // 1在一个功能相同的函数中,就像这样

//WARN... no undefined check here => todo !
function _(o, path) {
  var tmp = o
  for (var i=0 ; i < path.length ; i++) {
    tmp = tmp[path[i]]
  }
  return tmp
}

var r = _(a, ['A', 'AA'])

This is pretty much the same as other answers, but the difference is when dummy boy create object property name containing dots... Like var a = {"a.a" : 3 }is valid.

这与其他答案几乎相同,但不同之处在于当虚拟男孩创建包含点的对象属性名称时...... Likevar a = {"a.a" : 3 }是有效的。

Now, such problem would occurs maybe more often now with the help of IndexedDB to store anything locally...

现在,在 IndexedDB 的帮助下,这样的问题可能会更频繁地发生在本地存储任何东西......

回答by Agustí Sánchez

With lodash _.get function, you can access nested properties with dot syntax.

使用 lodash _.get 函数,您可以使用点语法访问嵌套属性。

Node server-side example:

节点服务器端示例:

const _ = require('lodash'); 

let item = { a: {b:'AA'}};

 _.get(item, 'a.b');