在对象js的嵌套数组中搜索
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在对象js的嵌套数组中搜索相关的知识,希望对你有一定的参考价值。
我有一个嵌套的对象数组,我试图在其中找到一个字符串。找到它后,我想返回包含的对象。这是我的代码:
const myArray = [
label: "Home",
last: "odlir",
children: [
label: "Home 1",
last: "odlir1",
children: [
label: "Home 2",
last: "odlir2"
,
label: "Home 3",
last: "odlir3"
]
,
label: "Home 4",
last: "odlir4",
children: [
label: "Home 5",
last: "odlir5"
,
label: "Home 6",
last: "odlir6"
]
]
,
label: "dash",
last: "gom"
,
label: "principal",
last: "asd"
];
function contain(obj, string)
if (obj == null)
return false;
if (obj.last == string)
return obj;
if (typeof obj.children == 'undefined')
return false;
for (let i = 0; i < obj.children.length; i++)
if (contain(obj.children[i], string))
return obj;
return false;
function getObject(array, string)
for (let i = 0; i < array.length; i++)
if (contain(array[i], string))
return array[i];
console.log('test', getObject(myArray, 'odlir6'));
我正在找回我想要的对象,父对象,甚至祖父。这是此代码的堆栈炸弹:https://stackblitz.com/edit/js-hgchmx
答案
您可以采用递归方法,并为每个嵌套调用存储paren对象。
function getObject(object, string, parent)
var result;
if (!object || typeof object !== 'object') return;
Object.values(object).some(v =>
if (v === string) return result = parent;
if (v && typeof v === 'object') return result = getObject(v, string, object);
);
return result;
const
array = [ label: "Home", last: "odlir", children: [ label: "Home 1", last: "odlir1", children: [ label: "Home 2", last: "odlir2" , label: "Home 3", last: "odlir3" ] , label: "Home 4", last: "odlir4", children: [ label: "Home 5", last: "odlir5" , label: "Home 6", last: "odlir6" ] ] , label: "dash", last: "gom" , label: "principal", last: "asd" ];
console.log(getObject(array, 'odlir6'));
以上是关于在对象js的嵌套数组中搜索的主要内容,如果未能解决你的问题,请参考以下文章