Javascript,读取记录的递归函数

时间:2018-03-06 22:46:33

标签: javascript arrays json

我正在尝试通过名为parent的列来读取彼此连接的记录,并且两侧的关系可以是一个或多个。

我尝试做一个递归函数,没有成功。我做了几次太复杂了,而且效果不好!你知道一个标准方法吗?

示例数据:

id       parent_id

Record1    main
RecordA1   Record1
RecordA2   Record1
RecordB1   RecordA1
RecordC1   RecordB1

我写的初始代码:

data.first_parent_id = main_parent_id;
data.categories = [];

function getCategories(parent_id) {
  // -> get data with column parent_id == parent_id input parameter
  data.categories.push({
    id: id,
    parent_id: gr.getValue('parent_id')
  });

  return data.categories;
}

getCategories(data.first_parent_id);

我正在尝试获取这样的对象数组:

  obj = {
    id: record1,
    children: [
      {
        id: RecordA1,
        children: [
          id: RecordB1,
          children: [
            id: RecordC1,
            children: [

            ]
          ]
        ]

      },
      {
        id: RecordA2,
        children: []
      },
      {
        id: value,
        children: []
      }
    ]
  };

有任何建议/提示吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

假设categories的结构如下:

此方法使用函数reduce和递归函数来查找父项。

//  id          parent_id
var categories = [
  ['Record1'],
  ['RecordA1', 'Record1'],
  ['RecordA2', 'Record1'],
  ['RecordB1', 'RecordA1'],
  ['RecordC1', 'RecordB1']
];



//  id          parent_id
var categories = [
  ['Record1'],
  ['RecordA1', 'Record1'],
  ['RecordA2', 'Record1'],
  ['RecordB1', 'RecordA1'],
  ['RecordC1', 'RecordB1']
];

var result = categories.reduce(function (acc, cat) {
  var id = cat[0], parent = cat[1];

  function findParent(obj) {
    if (obj.id === parent) return obj;
    else {
      if (obj.children) {
        for (var c of obj.children) {
          var f = findParent(c);
          if (f) return f;
        }
      }
    }
  }
  
  function getObject() {
    return { id: id, children: [] };
  }

  if (parent) {
    var found = findParent(acc);
    if (found) {
      found.children.push(getObject());
    } else {
      acc = Object.assign(acc, getObject());
    }
  } else {
    acc = getObject();
  };

  return acc;
}, {});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }