Javascript 不使用父对象访问对象子属性
我正在使用html2json,它返回一个包含子对象的对象。就像下面的代码。我想得到关键文本的值。但每种情况下,有多少子对象以及关键文本所在的位置都有所不同 我尝试过的代码,但由于这个原因,每次都不起作用,是这样的:Javascript 不使用父对象访问对象子属性,javascript,node.js,json,object,parent-child,Javascript,Node.js,Json,Object,Parent Child,我正在使用html2json,它返回一个包含子对象的对象。就像下面的代码。我想得到关键文本的值。但每种情况下,有多少子对象以及关键文本所在的位置都有所不同 我尝试过的代码,但由于这个原因,每次都不起作用,是这样的: json.child[0].child[0].child[0].child[0].text 这是一个对象的示例: node: 'root', child: [ { node: 'element', tag: 'div', attr
json.child[0].child[0].child[0].child[0].text
这是一个对象的示例:
node: 'root', child: [
{
node: 'element',
tag: 'div',
attr: { id: '1', class: 'foo' },
child: [
{
node: 'element',
tag: 'h2',
child: [
{ node: 'text', text: 'sample text with ' },
{ node: 'element', tag: 'code', child: [{ node: 'text', text: 'inline tag' }] }
]
}
]
} ]
是否有其他方法访问此元素?我想在对象中搜索一个键,因为键“文本”只出现一次。但我不知道这将如何工作
非常感谢您的帮助 您可以创建一个递归函数,该函数将返回键匹配的所有值的数组
const data={“node”:“root”、“child”:[{“node”:“element”、“tag”:“div”、“attr”:{“id”:“1”、“class”:“foo”},“child”:[{“node”:“element”、“tag”:“h2”、“child”:[{“node”:“text”、“text”:“sample text with”}、{“node”:“element”、“tag”:“code”、“child”:[{“node”:“text”、“text”:“inline tag”}]}]}]}
函数findByKey(数据、键){
常量结果=[];
for(让我输入数据){
if(i==键)result.push(数据[i]);
if(数据类型[i]=“对象”){
结果.推送(…findByKey(数据[i],键))
}
}
返回结果;
}
log(findByKey(data,'text'))
这是否回答了您的问题?