如何获得如此工作的方法getValueThroughPath(object, keysArray)
:
var object = {
key1: {
key2: {
key3: {
key4: "value"
}
}
}
}
getValueThroughPath(object, ['key1', 'key2', 'key3', 'key4']); // = "value" and undefined if wrong path
我也在寻找setValueThroughPath(object, keysArray)
等效方法。
如果可以缩短解决方案,我会使用Lodash。
答案 0 :(得分:2)
这会将对象向下移动到最后一个键。如果任何密钥拼写错误或丢失,则会返回undefined
:
function getValueThroughPath(obj, keys) {
while(obj=obj[keys.shift()] || '', keys.length);
return obj || undefined;
}
function setValueThroughPath(obj, keys, val) {
while(keys.length>1) {
obj[keys[0]]= obj[keys[0]] || {};
obj= obj[keys.shift()];
};
obj[keys[0]]= val;
}
var object = {
key1: {
key2: {
key3: {
key4: "value"
}
}
}
}
setValueThroughPath(object, ['this', 'is', 'a', 'test'], 'Eureka!');
setValueThroughPath(object, ['this', 'is', 'a', 'new', 'test'], 'Hallelujah!');
console.log(getValueThroughPath(object, ['key1', 'key2', 'key3', 'key4'])); // "value"
console.log(getValueThroughPath(object, ['key1', 'key2', 'key5', 'key4'])); // undefined
console.log(getValueThroughPath(object, ['this', 'is', 'a', 'test'])); // "Eureka!"
console.log(getValueThroughPath(object, ['this', 'is', 'a', 'new', 'test'])); // "Hallelujah!"
答案 1 :(得分:0)
您可以使用如下函数迭代对象属性并获取适当的值:
function getValueThroughPath(object, keys) {
var temp = object;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (temp.hasOwnProperty(key)) {
temp = temp[key];
console.log(JSON.stringify(temp));
} else {
console.log('Couldnt find key ' + key);
return undefined;
}
}
return temp;
}
您可以在http://jsfiddle.net/bx82akj5/查看小提琴,看它是否正常工作(打开控制台查看它!= D)
我使用了“hasOwnProperty”方法,因此您不会最终访问不存在的属性或访问javascript中的Object属性,因此您只能通过对象中定义的属性进行迭代。
您正在寻找的函数setValueTrhoughPath几乎相同(当然只是类似)