你如何从JavaScript的深层对象中获得结果?

时间:2018-04-29 13:53:46

标签: javascript function

期待结果:[“人”,“头”,“眼睛”]

离。

const data = {
  name: "human",
  children: [
    {
      name: "head",
      children: [
        {
          name: "eye"
        }
      ]
    },
    {
      name: "body",
      children: [
        {
          name: "arm"
        }
      ]
    }
  ]
}
const keyword = "eye"

使用上述数据并使用f函数获取结果

expect_result = f(data)

我应该写什么样的功能?

感谢。

3 个答案:

答案 0 :(得分:0)

尝试递归函数

const getData = items => {
   let fields = [];

   for (const item of items) {
     if (item.name) {
       fields.push(item.name);
     }

      if (Array.isArray(item.children)) {
        fields.push(...getData(item.children));  
      }
   }

   return fields;
}

答案 1 :(得分:0)

您可以通过检查属性或嵌套子项以获取所需值来使用迭代和递归方法。如果发现将名称取消移动到结果集中。

function getNames(object, value) {
    var names = [];
    [object].some(function iter(o) {
        if (o.name === value || (o.children || []).some(iter)) {
            names.unshift(o.name);
            return true;
        }
    });
    return names;
}

var data = { name: "human", children: [{ name: "head", children: [{ name: "eye" }] }, { name: "body", children: [{ name: "arm" }] }] };

console.log(getNames(data, 'eye'));
console.log(getNames(data, 'arm'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

var result = []   // This is outside the function since it get updated

function f(data) {
result.push(data.name);    // Add the only name to the Array

if (data.children) {   // just checking to see if object contains key children (staying safe)

for (var i = 0; i < data.children.length; i++) {  // we are only looping through the children

   f(data.children[i]);   // Call this particular function to do the same thing again

 }

}
}

基本上这个函数设置名称。然后遍历no子项,然后调用一个函数来设置该子项的名称,然后循环遍历其子项。这恰好是一个反作用的功能,直到它按顺序完成,所有这些