[英]Access object child property without using parent
我正在使用 html2json,它返回一个带有子对象的对象。 就像下面的代码。 我想获取关键文本的值。 但是每个情况下有多少子对象以及关键文本所在的位置都不同。
我尝试过的代码但由于这个原因,每次都不起作用是这个:
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"}]}]}]}]} function findByKey(data, key) { const result = []; for (let i in data) { if (i === key) result.push(data[i]); if (typeof data[i] === 'object') { result.push(...findByKey(data[i], key)) } } return result; } console.log(findByKey(data, 'text'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.