从 Javascript 中的递归函数返回对象数组 [英] Return an array of objects from a recursive function in Javascript

查看:67
本文介绍了从 Javascript 中的递归函数返回对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究递归函数.

我必须将所有具有键data: true"的对象推送到数组中.函数中间的 console.log 为我提供了单独数组中的所有对象.

I must push all objects that have the key "data: true" in an array. The console.log in the middle of my function gives me all those objects in separate arrays.

但是我无法返回一个包含对象的数组.我究竟做错了什么?谢谢

But I can't return an array with the objects at the end. What am I doing wrong? Thanks

const entries = {
  root: {
    data: true,
    key: "root",
    text: "some text"
  },
  test: {
    one: {
      two: {
        data: true,
        key: "test.one.two",
        text: "some text.again"
      },
      three: {
        data: true,
        key: "test.one.three",
        text: "some.more.text"
      }
    },
    other: {
      data: true,
      key: "test3",
      text: "sometext.text"
    }
  },
  a: {
    b: {
      data: true,
      key: "a.b",
      text: "a.b.text"
    },
    c: {
      d: {
        data: true,
        key: "a.c.d",
        text: "some.a.c.d"
      }
    }
  }
};


function recursiveFunc(data) {
  let tab = [];
  for (let property in data) {
    if (data.hasOwnProperty(property)) {
      if (data[property].data === true) {
        tab.push(data[property]);
        console.log("t", tab);
      } else {
        recursiveFunc(data[property])
      }
    }
  }
  return tab
}

console.log(recursiveFunc(entries));

推荐答案

在递归调用上添加 tab.concat() 以加入递归 fn 返回的项目.

Add tab.concat() on the recursive call for join the items returned by the recursive fn.

const entries = {
  root: {
    data: true,
    key: "root",
    text: "some text"
  },
  test: {
    one: {
      two: {
        data: true,
        key: "test.one.two",
        text: "some text.again"
      },
      three: {
        data: true,
        key: "test.one.three",
        text: "some.more.text"
      }
    },
    other: {
      data: true,
      key: "test3",
      text: "sometext.text"
    }
  },
  a: {
    b: {
      data: true,
      key: "a.b",
      text: "a.b.text"
    },
    c: {
      d: {
        data: true,
        key: "a.c.d",
        text: "some.a.c.d"
      }
    }
  }
};


function recursiveFunc(data) {
  let tab = [];
  for (let property in data) {
    if (data.hasOwnProperty(property)) {
      if (data[property].data === true) {
        tab.push(data[property]);
        console.log("t", tab);
      } else { 
        tab = tab.concat(recursiveFunc(data[property]));
      }
    } 
  } 
  return tab
}
console.log(recursiveFunc(entries));

这篇关于从 Javascript 中的递归函数返回对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆