Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I convert JSON with nested children to an array whic contain parent_id, Thank you !

var json = {  
        id: "1",  
        name: "loreim ipsum",  
        data: {},  
        children: [{  
            id: "2",  
            name: "lorem ipsum1",  
            data: {},  
            children: [{  
                id: "3",  
                name: "lorem ipsum2",  
                data: {},  
                children: [{
                ..............

to an array like this

array(
    array('id' => 1, 'parent_id' => null, 'name' => 'lorem ipsum'),
    array('id' => 2, 'parent_id' => 1, 'name' => 'lorem ipsum1'),
    array('id' => 3, 'parent_id' => 1, 'name' => 'lorem ipsum2'),
    array('id' => 4, 'parent_id' => 2, 'name' => 'lorem ipsum3'),
    array('id' => 5, 'parent_id' => 3, 'name' => 'lorem ipsum4'),
    array('id' => 6, 'parent_id' => null, 'name' => 'lorem ipsum5'),
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
333 views
Welcome To Ask or Share your Answers For Others

1 Answer

Recursively build a flat array -

var json = {
  id: "1",
  name: "loreim ipsum",
  data: {},
  children: [{
    id: "2",
    name: "lorem ipsum1",
    data: {},
    children: [{
        id: "3",
        name: "lorem ipsum2",
        data: {},
        children: [{
          id: "4",
          name: "lorem ipsum2",
          data: {}
        }]
      },
      {
        id: "5",
        name: "lorem ipsum2",
        data: {},
        children: [{
          id: "6",
          name: "lorem ipsum2",
          data: {}
        }]
      }
    ]
  }]
}

function flat(array, parentId) {
  var result = [];
  array.forEach(function(a) {

    var newObject = Object.assign({}, a);
    delete newObject.children;
    newObject.parent_id = parentId;
    result.push(newObject);
    if (Array.isArray(a.children)) {
      result = result.concat(flat(a.children, a.id));
    }
  });
  return result;
}

console.log(flat([json], null));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...