Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
Get value from nested arrays of objects

I have data that is structured like the following:

const arr = [{
    id: 0,
    name: 'Biomes',
    icon: 'mdi-image-filter-hdr',
    isParent: true,
    children: [{
        id: 1,
        name: 'Redwood forest',
        icon: 'mdi-image-filter-hdr'
    }]
},{
    id: 2,
    name: 'Trees',
    icon: 'mdi-pine-tree',
    children: [{
        id: 8,
        name: 'Redwood',
        icon: 'mdi-pine-tree'
    }]
}];

The top level is an array of objects, and each object can have a child field children which itself can be an array of objects. If I know the value of id, how can I find the object (or more importantly the object name), based on that id value?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use recursion here to get the object no matter how deep it is. I've filtered out the object. It will only give the object without children property. You can include it in the way you want

function getObjectFromId(arr, id) {
  for (let i = 0; i < arr.length; ++i) {
    if (arr[i].id === id) {
     // return arr[i]   // If you want full object with children
      const { children, ...rest } = arr[i];
      return rest;
    }
    if (arr[i].children) {
      const result = getObjectFromId(arr[i].children, id);
      if (result) return result;
    }
  }
}

const arr = [
  {
    id: 0,
    name: "Biomes",
    icon: "mdi-image-filter-hdr",
    isParent: true,
    children: [
      {
        id: 1,
        name: "Redwood forest",
        icon: "mdi-image-filter-hdr",
      },
    ],
  },
  {
    id: 2,
    name: "Trees",
    icon: "mdi-pine-tree",
    children: [
      {
        id: 8,
        name: "Redwood",
        icon: "mdi-pine-tree",
        children: [
          {
            id: 9,
            name: "Redwood",
            icon: "mdi-pine-tree",
          },
        ],
      },
    ],
  },
];

function getObjectFromId(arr, id) {
  for (let i = 0; i < arr.length; ++i) {
    if (arr[i].id === id) {
      // return arr[i]   // If you want full object with children
      const { children, ...rest } = arr[i];
      return rest;
    }
    if (arr[i].children) {
      const result = getObjectFromId(arr[i].children, id);
      if (result) return result;
    }
  }
}

console.log(getObjectFromId(arr, 1));
console.log(getObjectFromId(arr, 8));
console.log(getObjectFromId(arr, 9));
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

const arr = [{
    id: 0,
    name: 'Biomes',
    icon: 'mdi-image-filter-hdr',
    isParent: true,
    children: [{
        id: 1,
        name: 'Redwood forest',
        icon: 'mdi-image-filter-hdr'
    }]
},{
    id: 2,
    name: 'Trees',
    icon: 'mdi-pine-tree',
    children: [{
        id: 0,
        name: 'whatever',
        icon: 'new-tree'
    },{
        id: 8,
        name: 'Redwood',
        icon: 'mdi-pine-tree'
    }]
}];

const findById = (id) => arr
    .filter(x => x.id === id || x.children.some(child => id === child.id))
    .map(y => ({...y, children: y.children.filter(child => id === child.id)}))

console.log(findById(0))

You can first filter out all parents who has the same id or if the parent has child with same id via some, which then using map to and filter to remove all children who don't have the id

about 4 years ago · Juan Pablo Isaza Relatório

0

Solution 1: 2 for loop.

const inputArray = [{
    id: 0,
    name: 'Biomes',
    icon: 'mdi-image-filter-hdr',
    isParent: true,
    children: [{
      id: 1,
      name: "Redwood forest",
      icon: 'mdi-image-filter-hdr'
    }]
  },
  {
    id: 2,
    name: 'Trees',
    icon: 'mdi-pine-tree',
    children: [{
      id: 8,
      name: "Redwood",
      icon: 'mdi-pine-tree',
    }]
  }
];

console.log(findById(8));

function findById(id) {
  for (const parent of inputArray) {
    if (parent.id === id)
      return parent;     
    for (const child of parent.children)
      if (child.id === id)
        return child;
  }
  return null;
}

Solution 2: multiple nested level:

const inputArray = [{
    id: 0,
    name: 'Biomes',
    icon: 'mdi-image-filter-hdr',
    isParent: true,
    children: [{
      id: 1,
      name: "Redwood forest",
      icon: 'mdi-image-filter-hdr'
    }]
  },
  {
    id: 2,
    name: 'Trees',
    icon: 'mdi-pine-tree',
    children: [{
      id: 8,
      name: "Redwood",
      icon: 'mdi-pine-tree',
      children: [{
        id: 12,
        name: "Test Level 2",
        icon: 'mdi-pine-tree',
        children: [{
          id: 13,
          name: "Test Level 3",
          icon: 'mdi-pine-tree',
        }]
      }]
    }]
  }
];

console.log(findById(13, inputArray));

function findById(id, array) {
  for (const parent of array) {
    if (parent.id === id)
      return parent;

    if ('children' in parent) {
      const result = findById(id, parent.children);
      if (result) return result;
    }
  }

  return null;
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda