this answer的实用程序函数允许轻松访问对象的嵌套属性,并在父属性不存在时返回null (或未定义)。
原始代码:
get =函式(obj,key) {传回key.split(“.”).reduce(函式(o,x) {传回(输入o == )“未定义的”\x === null)?O: ox;},obj);}get(用户,'loc.lat') // 50 get(用户,'loc.foo.bar') //未定义
我真的很想使用这个,但是我也需要能够处理嵌套数组。
示例:
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]"
(不需要regex删除方括号.)?
您知道一个更优雅的解决方案吗?它能实现上述示例中的结果吗?
发布于 2016-05-18 11:23:24
最简单的方法是更改传递给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
发布于 2016-05-18 11:22:34
通过Object.prototype.getNestedValue()
的发明,您可以通过对象属性和数组索引动态访问深度嵌套的值。您所要做的就是以正确的顺序动态提供嵌套属性和索引作为参数。
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var arr = [{fox: [{turn:[857, 432]}]}, {sax: [{pana:[777, 987]}]}, {ton: [{joni:[123, 567]}]}, {piu: [{burn:[666, 37]}]}, {sia: [{foxy:[404, 696]}]}],
myObj = { foo : 1, bar: { baz : 2 }, bee : 3 },
arg1 = 3,
arg2 = "piu",
arg3 = 0,
arg4 = "burn",
arg5 = 1;
document.write(arr.getNestedValue(arg1,arg2,arg3,arg4,arg5));
发布于 2016-05-18 10:33:04
相反,我将使用一个属性名称数组,这将允许您轻松地递归。
但是,如果您想回到原来的模式,仍然可以将表达式转换为这个数组。
请看一下这个示例:
var innerget = function(object, proparr) {
if(proparr.length == 0)
return object;
if(typeof object == "undefined" || object === null)
return object;
return innerget(object[proparr.splice(0, 1)], proparr);
};
var get = function(object, expr) {
var proparr = expr.replace(/\[/g, ".").replace(/\]/g, "").split(".");
return innerget(object, proparr);
}
var object = {
key: [[1, 2, 3], [4, 5, 6]]
};
document.write(innerget(object, ['key', 'key2', 2]) + "<br>");
document.write(innerget(object, ['key', 0, 2]) + "<br>");
document.write(get(object, "key[0][1]"));
https://stackoverflow.com/questions/37296490
复制相似问题