J'ai un tableau d'objets contenant des informations sur des données imbriquées et je souhaite convertir les données en données de tableau imbriquées réelles. Comment puis-je convertir ceci:

const data = [
  {id: 1, parent_id: null, name: 'test1'},
  {id: 2, parent_id: null, name: 'test2'},
  {id: 3, parent_id: 2, name: 'test3'},
  {id: 4, parent_id: 2, name: 'test4'},
  {id: 5, parent_id: 4, name: 'test5'},
  {id: 6, parent_id: 4, name: 'test5'},
  {id: 7, parent_id: 2, name: 'test5'},
  {id: 8, parent_id: 2, name: 'test5'},
  {id: 9, parent_id: null, name: 'test5'},
  {id: 10, parent_id: null, name: 'test5'},
]

Pour ça:

const data = [
  {id: 1, parent_id: null, name: 'test1'},
  {
    id: 2, 
    parent_id: null, 
    name: 'test2',
    children: [
      {id: 3, parent_id: 2, name: 'test3'},
      {
        id: 4, 
        parent_id: 2, 
        name: 'test4',
        children: [
          {id: 5, parent_id: 4, name: 'test5'},
          {id: 6, parent_id: 4, name: 'test5'}
        ]
      },
      {id: 7, parent_id: 2, name: 'test5'},
      {id: 8, parent_id: 2, name: 'test5'},
    ]
  },
  {id: 9, parent_id: null, name: 'test5'},
  {id: 10, parent_id: null, name: 'test5'},
]

Quelle est la meilleure façon de procéder?

7
Dan 20 nov. 2018 à 18:21

5 réponses

Meilleure réponse

Vous pouvez créer une fonction récursive avec la méthode reduce pour cela.

const data = [{id: 1, parent_id: null, name: 'test1'},{id: 2, parent_id: null, name: 'test2'},{id: 3, parent_id: 2, name: 'test3'},{id: 4, parent_id: 2, name: 'test4'},{id: 5, parent_id: 4, name: 'test5'},{id: 6, parent_id: 4, name: 'test5'},{id: 7, parent_id: 2, name: 'test5'},{id: 8, parent_id: 2, name: 'test5'},{id: 9, parent_id: null, name: 'test5'},{id: 10, parent_id: null, name: 'test5'},]

function nest(data, parentId = null) {
  return data.reduce((r, e) => {
    let obj = Object.assign({}, e)
    if (parentId == e.parent_id) {
      let children = nest(data, e.id)
      if (children.length) obj.children = children
      r.push(obj)
    }
    return r;
  }, [])
}

console.log(nest(data))
3
Nenad Vracar 20 nov. 2018 à 15:34

C'est un problème intéressant. Une option si vous souhaitez conserver un temps linéaire au détriment d'un peu d'espace pour créer un objet de recherche basé sur id. Ensuite, vous pouvez parcourir ces valeurs et pousser dans un objet parent ou le tableau:

const data = [{id: 1, parent_id: null, name: 'test1'},{id: 2, parent_id: null, name: 'test2'},{id: 3, parent_id: 2, name: 'test3'},{id: 4, parent_id: 2, name: 'test4'},{id: 5, parent_id: 4, name: 'test5'},{id: 6, parent_id: 4, name: 'test5'},{id: 7, parent_id: 2, name: 'test5'},{id: 8, parent_id: 2, name: 'test5'},{id: 9, parent_id: null, name: 'test5'},{id: 10, parent_id: null, name: 'test5'},]

let lookup = data.reduce((obj, item) => {
  obj[item.id] = item
  return obj
}, {})

let arr = Object.values(lookup).reduce((arr, val) =>{
  if (val.parent_id == null) arr.push(val)
  else (lookup[val.parent_id].children || ( lookup[val.parent_id].children = [])).push(val)
  
  return arr
}, [])

console.log(JSON.stringify(arr, null, 2))
1
Mark Meyer 20 nov. 2018 à 15:56

Vous pouvez adopter une approche à boucle unique en utilisant un objet et les clés id et parent_id et collecter les éléments / enfants.

L'ordre n'est important que pour l'ordre dans le tableau des enfants.

const
    data = [{ id: 1, parent_id: null, name: 'test1' }, { id: 2, parent_id: null, name: 'test2' }, { id: 3, parent_id: 2, name: 'test3' }, { id: 4, parent_id: 2, name: 'test4' }, { id: 5, parent_id: 4, name: 'test5' }, { id: 6, parent_id: 4, name: 'test5' }, { id: 7, parent_id: 2, name: 'test5' }, { id: 8, parent_id: 2, name: 'test5' }, { id: 9, parent_id: null, name: 'test5' }, { id: 10, parent_id: null, name: 'test5' }],
    tree = function (data, root) {
        var t = {};
        data.forEach(o => {
            Object.assign(t[o.id] = t[o.id] || {}, o);
            t[o.parent_id] = t[o.parent_id] || {};
            t[o.parent_id].children = t[o.parent_id].children || [];
            t[o.parent_id].children.push(t[o.id]);
        });
        return t[root].children;
    }(data, null);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
2
Nina Scholz 12 nov. 2019 à 09:59

Vous pouvez essayer cette approche récursive

const data = [{id: 1, parent_id: null, name: 'test1'}, {id: 2, parent_id: null, name: 'test2'}, {id: 3, parent_id: 2, name: 'test3'}, {id: 4, parent_id: 2, name: 'test4'}, {id: 5, parent_id: 4, name: 'test5'}, {id: 6, parent_id: 4, name: 'test5'}, {id: 7, parent_id: 2, name: 'test5'}, {id: 8, parent_id: 2, name: 'test5'}, {id: 9, parent_id: null, name: 'test5'}, {id: 10, parent_id: null, name: 'test5'}];

const transform = arr => {
  return arr.reduce((acc, elem) => {
     const children = data.filter(el => el.parent_id === elem.id),
           isPresent = findDeep(acc, elem);
     if(!isPresent && children.length)
       acc.push({...elem, children: transform(children)});
     else if(!isPresent)
       acc.push(elem);
     return acc;
  }, []);
}


const findDeep =(arr = [], elem) => (
   arr.some(el => (el.id === elem.id) || findDeep(el.children, elem))
);

console.log(transform(data));
0
Karim 20 nov. 2018 à 17:07
const data = [
  {id: 1, parent_id: null, name: 'test1'},
  {id: 2, parent_id: null, name: 'test2'},
  {id: 3, parent_id: 2, name: 'test3'},
  {id: 4, parent_id: 2, name: 'test4'},
  {id: 5, parent_id: 4, name: 'test5'},
  {id: 6, parent_id: 4, name: 'test5'},
  {id: 7, parent_id: 2, name: 'test5'},
  {id: 8, parent_id: 2, name: 'test5'},
  {id: 9, parent_id: null, name: 'test5'},
  {id: 10, parent_id: null, name: 'test5'},
]

const output = data.filter(
  item => !item.parent_id
).map(
  rootItem => ({
    ...rootItem,
    children: data.filter(item => item.parent_id === rootItem.id),
  })
)

console.log(output)
-1
alexjackson 20 nov. 2018 à 15:35