访问JavaScript中的嵌套数组/属性

硬件

此答案中的实用程序功能允许轻松访问对象的嵌套属性,如果父属性之一不存在,则返回null(或未定义)。

原始代码:

get = function(obj, key) {
    return key.split(".").reduce(function(o, x) {
        return (typeof o == "undefined" || o === null) ? o : o[x];
    }, obj);
}
 get(user, 'loc.lat')     // 50
 get(user, 'loc.foo.bar') // undefined

我真的很想使用它,但是我也需要能够使用嵌套数组。

例子:

var childArray = [0,1,2]
var parentArray = [{myArray: childArray}]
var obj = {key: parentArray}

我想像这样扩展实用程序功能:

get(obj, 'key[0].myArray[2]');      // 2
get(obj, 'key[0].foo[2]');          // null
get(obj, 'key[0].myArray[42]');     // null

理想情况下,它也应该能够对此进行评估

var childArray = [0,1,2]
var parentArray = [childArray, childArray]
var obj = {key: parentArray}

get(obj, 'key[1][0]');     // 0
get(obj, 'foo[1][0]');     // null

问题:

是否可以使用arr给定的字符串引用访问数组"arr[0]"不使用正则表达式删除括号...)?

您是否知道一种更优雅的解决方案,可以实现以上示例中呈现的结果?

安德烈亚斯(Andreas)

最简单的方法是更改​​要传递给的路径/密钥 get()

get(obj, 'key[0].myArray[2]');

get(obj, 'key.0.myArray.2');

var get = function(obj, key) {
    return key.split(".").reduce(function(o, x) {
        return (typeof o == "undefined" || o === null) ? o : o[x];
    }, obj);
}

var childArray = [0,1,2]
var parentArray = [{myArray: childArray}]
var obj = {key: parentArray}

console.log(get(obj, 'key.0.myArray.2'));      // 2
console.log(get(obj, 'key.0.foo.2'));          // null
console.log(get(obj, 'key.0.myArray.42'));     // null

var childArray2 = [0,1,2]
var parentArray2 = [childArray2, childArray2]
var obj2 = {key: parentArray2}

console.log(get(obj2, 'key.1.0'));     // 0
console.log(get(obj2, 'foo.1.0'));     // null

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章