【问题标题】:Build flat array from tree array in node js从节点js中的树数组构建平面数组
【发布时间】:2019-10-12 22:46:59
【问题描述】:

我有同一个数组,不限级别,不限于三个级别-它是n级别数组。

最后parent_id = null;

输入数组:

{
  parent_id: {
    parent_id: {
      parent_id: null,
      _id: 5cdfcc1fb214df2da06bd0dc,
      title: 'Home & Kitchen'
    },
    _id: 5cdfcc45b214df2da06bd0dd,
    title: 'Furniture'
  },
  _id: 5cdfcc74b214df2da06bd0de,
  title: 'Sofas'
}

预期输出数组:

[
  {
      _id: 5cdfcc74b214df2da06bd0de,
      title: 'Sofas'
  },
  {
      _id: 5cdfcc45b214df2da06bd0dd,
      title: 'Furniture'
  },
  {
      _id: 5cdfcc1fb214df2da06bd0dc,
      title: 'Home & Kitchen'
  }
]

【问题讨论】:

  • 请发布您已经尝试过的内容。
  • 我尝试了 forEach() 和 map() 但我没有解决。

标签: node.js json mongoose populate


【解决方案1】:

function getResult(input) {
  const result = [];
  let curr = input;
  while(curr){ 
     result.push({
         _id: curr._id,
         title: curr.title
     });
     curr = curr.parent_id; // if there is no parent_id inside, cycle will stop
  }
  return result;
}

let testInput = {
  parent_id: {
    parent_id: {
      parent_id: null,
      _id: '5cdfcc1fb214df2da06bd0dc',
      title: 'Home & Kitchen'
    },
    _id: '5cdfcc45b214df2da06bd0dd',
    title: 'Furniture'
  },
  _id: '5cdfcc74b214df2da06bd0de',
  title: 'Sofas'
};

console.log(getResult(testInput));

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2016-09-25
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多