[英]Traverse through multi-dimentional object
I have a multi-dimensional object:我有一个多维对象:
var obj = {
prop: {
myVal: "blah",
otherVal: {
// lots of other properties
},
},
};
How would one traverse the entire object, without knowing any of the property names or the number of "dimensions" in the object?在不知道对象中的任何属性名称或“维度”数量的情况下,如何遍历整个对象?
There are a couple other questions on SO that are related to the topic:关于 SO 的其他几个问题与该主题相关:
Traverse through Javascript object properties 遍历 Javascript 对象属性
javascript traversing through an object javascript遍历一个对象
The problem is that both answers are not quite what I am looking for, because:问题是这两个答案都不是我想要的,因为:
a) The first link only iterates through the first layer in the object. a)第一个链接只遍历对象中的第一层。
b) The second answer requires you to know the names of the object's keys. b)第二个答案要求您知道对象键的名称。
Recursion:递归:
function doSomethingWithAValue(obj, callback) {
Object.keys(obj).forEach(function(key) {
var val = obj[key];
if (typeof val !== 'object') {
callback(val);
} else {
doSomethingWithAValue(val, callback);
}
});
}
Consider using object-scan .考虑使用object-scan 。 It's powerful for data processing once you wrap your head around it.一旦你把头环绕在它周围,它对于数据处理来说是强大的。 Here is how you'd do a simple iteration in delete safe order:以下是您如何以安全删除的顺序进行简单的迭代:
// const objectScan = require('object-scan'); const obj = { prop: { myVal: 'blah', otherVal: { /* lots of other properties */ } } }; objectScan(['**'], { filterFn: ({ key, value }) => { console.log(key, value); } })(obj); // => [ 'prop', 'otherVal' ] {} // => [ 'prop', 'myVal' ] blah // => [ 'prop' ] { myVal: 'blah', otherVal: {} }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>
Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.