Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
How can I number my points and subpoints which has an unlimited number of nested objects using recursive function and js

let's say I have data something like this

    let data = [
    {
        subPoint:[
            {
                point:'point a 1.1',
            },
            {
                point:'point a 1.2',
            },
            {
                subPoint:[
                    {
                        subPoint:[
                            {
                                point:'point a 1.3.1.1'
                            }
                        ]
                    },
                    {
                        point:'point a 1.3.1.2'
                    }
                ]
            },
        ]
    },
    {
        point:'point b 1'
    },
    {
        point:'point c 1'
    },
    {
        subPoint:[
            {
                subPoint:[
                    {
                        point:'point d 1.1.1'
                    }
                ]
            }
        ]
    }
]

My intended result should be something like this

[
  '1.1.1---point a 1.1',
  '1.1.2---point a 1.2',
  '1.1.3.1.1---point a 1.3.1.1',
  '1.1.3.1.2---point a 1.3.1.2',
  '2.1---point b 1',
  '3.1---point c 1',
  '4.1.1.1---point d 1.1.1'
]

But what I am getting is this

[
  '1.3.1---point a 1.1',
  '1.3.2---point a 1.2',
  '1.3.3.1.1.1---point a 1.3.1.1',
  '1.3.3.1.2---point a 1.3.1.2',
  '2---point b 1',
  '3---point c 1',
  '4.1.1.1---point d 1.1.1'
]

my code looks like this

const getInfo = (starIndex,array) => {
    let rowId = starIndex
    array.forEach((val,ind) => {
        if(val.subPoint){
            console.log(starIndex)
            rowId = starIndex+'.'+(ind+1)

            return getInfo(rowId,val.subPoint)
        }
    })
    console.log('rowId',rowId)
    return rowId
}
let returnData = []
const getData = (_data,val) => {

    _data.forEach((_dat,index) => {
        let value = (val?`${val}.`:'')+`${index+1}`
        if(_dat.subPoint){
            value = getInfo(value,_dat.subPoint)
            getData(_dat.subPoint,value)
        }else {
            returnData.push(value+ '---' + _dat.point)
        }
    })
    return returnData
}

console.log(getData(data))

I think I missing something or my recursion is bad I am not sure what the issue is,

This is a metaphorical code for a problem I have the actual problem has to do deal with giving a unique id for each table row component which can have any number of grouping.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Without extra levels.

const
    getFlat = (parent = '') => ({ point, subPoint = [] }, i) => {
        const
            p = parent + (parent && '.') + (i + 1),
            children = subPoint.flatMap(getFlat(p));

        if (point) children.unshift([p, point].join('---'));

        return children;
    },
    data = [{ subPoint: [{ point: 'point a 1.1' }, { point: 'point a 1.2' }, { subPoint: [{ subPoint: [{ point: 'point a 1.3.1.1' }] }, { point: 'point a 1.3.1.2' }] }] }, { point: 'point b 1' }, { point: 'point c 1' }, { subPoint: [{ subPoint: [{ point: 'point d 1.1.1' }] }] }],
    result = data.flatMap(getFlat());

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

const data = [
  {
    subPoint: [
      {
        point: 'point a 1.1',
      },
      {
        point: 'point a 1.2',
      },
      {
        subPoint: [
          {
            subPoint: [
              {
                point: 'point a 1.3.1.1',
              },
            ],
          },
          {
            point: 'point a 1.3.1.2',
          },
        ],
      },
    ],
  },
  {
    point: 'point b 1',
  },
  {
    point: 'point c 1',
  },
  {
    subPoint: [
      {
        subPoint: [
          {
            point: 'point d 1.1.1',
          },
        ],
      },
    ],
  },
];
const flatten = (data) => {
  let result = [];
  const recurse = (data, path = '') => {
    for (let i = 0; i < data.length; i++) {
      let item = data[i];
      let newPath = path ? `${path}.${i + 1}` : `${i + 1}`;
      if (item.point) {
        result.push(`${newPath}---${item.point}`);
      } else {
        recurse(item.subPoint, newPath);
      }
    }
  };
  recurse(data);
  return result;
}
console.log(flatten(data));

about 4 years ago · Juan Pablo Isaza Denunciar

0

This output does not match your request, but it seems much more logical to me:

[
  "1.1---point a 1.1",
  "1.2---point a 1.2",
  "1.3.1.1---point a 1.3.1.1",
  "1.3.2---point a 1.3.1.2",
  "2---point b 1",
  "3---point c 1",
  "4.1.1---point d 1.1.1"
]

If that works for you, here is a simple recursion that will generate it:

const outline = (xs, path = []) => xs .flatMap (({point, subPoint = []}, i) => point 
  ? [`${path .concat (i + 1) .join ('.')}---${point}`] 
  : outline (subPoint, path .concat (i + 1))
)

const data = [{subPoint: [{point: "point a 1.1"}, {point: "point a 1.2"}, {subPoint: [{subPoint: [{point: "point a 1.3.1.1"}]}, {point: "point a 1.3.1.2"}]}]}, {point: "point b 1"}, {point: "point c 1"}, {subPoint: [{subPoint: [{point: "point d 1.1.1"}]}]}]

console .log (outline (data))
.as-console-wrapper {max-height: 100% !important; top: 0}

We track a running path, that might contain values such as [2] or [1, 3, 1, 1], and on each call, if we've hit a node with a point property we combine the path with that property string. If we haven't we add the current index (plus one to deal with JS's zero-based counting) to the path, and recur on the children of the subPoint node.

If that output doesn't work, can you explain exactly where each of your target outline prefixes comes from?

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda