简体   繁体   中英

Javascript, recursive function to read records

I'm trying to read records that are connected to each other through a column called parent, and the relation can be one or many on both sides.

I tried to do a recursive function, without success. I made it several times too complex and furthermore it was not working very well! Do you know a standard approach for this?

Sample data:

id       parent_id

Record1    main
RecordA1   Record1
RecordA2   Record1
RecordB1   RecordA1
RecordC1   RecordB1

Initial code I wrote:

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);

I am trying to obtain an object array like this:

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

            ]
          ]
        ]

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

Any suggestions/hints?

Thanks a lot

Assuming the structure of categories is as follow:

This approach uses the function reduce along with a recursive function to find parents.

//  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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM