Javascript反思:获取嵌套对象的路径 [英] Javascript reflection: Get nested objects path
问题描述
在这个stackoverflow线程中,我了解到可以通过一个简单的字符串获取对象路径.
In this stackoverflow thread, i learnt you can get a object path via a simple string.
请考虑以下内容:
var person = { name: "somename", personal: { weight: "150", color: "dark" }};
var personWeight = deep_value(person,"personal.weight");
我试图从我的人"对象构造一个不是对象"类型的对象值的数组.
I an trying to construct an array of the object values who are not of type 'object' from my 'person' object.
因此数组如下所示:
[['name', []],['personal.weight', []],['personal.color', []]];
我希望他们使用该表格,因为我会在以后进一步使用它.
I want them to look in that form because i have further use for it down the road.
这就是我尝试过的:
var toIterate = { name: "somename", personal: { age: "19", color: "dark" } }
var myArray = [];
$.each(toIterate, recursive);
function recursive(key, value) {
if (key !== null) {
myArray.push([key, []]);
}
else {
$.each(value, recursive);
}
}
console.log(myArray);
推荐答案
只需使用递归来遍历对象.
Just use recursion to walk the object.
var person = {
name: "somename",
personal: {
weight: "150",
color: "dark",
foo: {
bar: 'bar',
baz: 'baz'
},
empty: {
}
}
};
// however you want to do this
var isobject = function(x){
return Object.prototype.toString.call(x) === '[object Object]';
};
var getkeys = function(obj, prefix){
var keys = Object.keys(obj);
prefix = prefix ? prefix + '.' : '';
return keys.reduce(function(result, key){
if(isobject(obj[key])){
result = result.concat(getkeys(obj[key], prefix + key));
}else{
result.push(prefix + key);
}
return result;
}, []);
};
var keys = getkeys(person);
document.body.innerHTML = '<pre>' + JSON.stringify(keys) + '</pre>';
然后使用Array.prototype.map
将键数组按摩成您喜欢的格式.
注意person.personal.empty
的行为.
Then use Array.prototype.map
to massage the array of keys into your preferred format.
Note the behaviour with person.personal.empty
.
这似乎是一种存储对象键的奇怪方法.我想知道您的进一步用途"是什么.
This does seem like a strange way to store an object's keys. I wonder what your 'further use for it down the road' is.
这篇关于Javascript反思:获取嵌套对象的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!