通过属性名称递归搜索对象中的值 [英] Search recursively for value in object by property name
本文介绍了通过属性名称递归搜索对象中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个实用程序函数,该函数应搜索属性名称并在找到后返回其值.它应该递归执行此操作:
I'm building an utility function that should search for a property name and return its value once it is found. It should do this recursively:
// Function
util.findVal = (object, propName) => {
for (let key in object) {
if (key === propName) {
console.log(propName)
console.log(object[key])
return object[key]
} else {
util.findVal(object[key], propName)
}
}
}
// Input
object: {
photo: {
progress: 20
}
}
// Usage
util.findVal(object, 'progress')
但是,控制台日志永远消失并且浏览器崩溃.我在做什么错了?
However the console log goes forever and the browser crashes. What am I doing wrong?
这就是我调用该函数的方式:
This is how I'm calling the function:
// Input
item: {
photo: {
file: {},
progress: 20
}
}
this.findProgress(item)
methods: {
findProgress (item) {
return util.findVal(item, this.propName)
}
}
推荐答案
您可以使用 Array#some
.
You could use Object.keys
and iterate with Array#some
.
function findVal(object, key) {
var value;
Object.keys(object).some(function(k) {
if (k === key) {
value = object[k];
return true;
}
if (object[k] && typeof object[k] === 'object') {
value = findVal(object[k], key);
return value !== undefined;
}
});
return value;
}
var object = { photo: { progress: 20 }};
console.log(findVal(object, 'progress'));
这篇关于通过属性名称递归搜索对象中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文