如何从javascript中的值获取对象值的路径 [英] how to get the path of an object's value from a value in javascript
本文介绍了如何从javascript中的值获取对象值的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例:
var someObject = {
'part1' : {
'name': 'Part 1',
'txt': 'example',
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}, {
'name': '[value]',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]};
我需要一个函数来将对象的路径变为值 [value]
可以是对象上的任何地方
I need a function to get the path of the object to the value "[value]"
which can be anywhere on the object
此对象将由用户传递,因此我不知道它的结构。
This object will be passed by the User, for this reason I will not know the structure of it.
类似于:
getPath(obj, '[value]');
推荐答案
这里有一些代码可以让你找到你的路径对象,不确定它是多么安全:
Here's some code that should get you a path to your object, not sure how super safe it is:
function getPath(obj, val, path) {
path = path || "";
var fullpath = "";
for (var b in obj) {
if (obj[b] === val) {
return (path + "/" + b);
}
else if (typeof obj[b] === "object") {
fullpath = getPath(obj[b], val, path + "/" + b) || fullpath;
}
}
return fullpath;
}
其中 testObj
是示例中的对象:
console.log(getPath(testObj, '20')); // Prints: /part3/2/qty
console.log(getPath(testObj, "[value]")); // Prints: /part3/1/name
这篇关于如何从javascript中的值获取对象值的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文