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

216
Visualizações
How can i find parent from nested object ? (Javascript)

I have a nested object. I need a function. I need use it for find "parent key" Which function should i use for it ? My data :

[{
    "Name": "Main Menu",
    "Key": "1",
    "Children": [{
      "Name": "Sub Menu 1",
      "Key": "10",
      "Children": [{
        "Name": "Very Sub Menu",
        "Key": "20",
        "Children": []
      }]
    }]
  },
  {
    "Name": "Main Menu 2",
    "Key": "2",
    "Children": [{
      "Name": "Sub Menu 2",
      "Key": "11",
      "Children": [{
        "Name": "Very Sub Menu 2",
        "Key": "21",
        "Children": [{
          "Name": "Extra Small Menu",
          "Key": "30",
          "Children": []
        }]
      }]
    }]
  }
]

For example when I send my array and key (For example "10"(Sub Menu 1) for that example) I need take 1 as a result (Main Menu Key.)

Example 2 : If I give 30 as a key ; I need take 21 as a result. How can I do it ? Thanks for replies!

I tried like :

var res = myData.filter(function f(o) {
      if (o.key === dragKey) return true;

      if (o.children) {
        return (o.children = o.children.filter(f)).length;
      }
    });
    console.log(res); // Its giving main whole data main level to child level. I need just 1 upper level data.
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could use recursion for this. Loop through the object with

const findObjectByKey = (parent, object, key) => {
    // make object optional because the first iteration is null
    if (object?.key === key) return parent
    for (const obj of Object.entries(object.children)) {
      return findObjectByKey(object, obj, key)
    }
}

const finalparent = findObjectByKey(null, object, 30)

NOTE: This is untested pseudo code just to give you an idea how I would solve it.

about 4 years ago · Juan Pablo Isaza Relatório

0

You should write a recursive function that takes an array as input. loop over array's items and check if the key matches, if it does so return a result that declares you have found the child. Then in the parent return the parent id at every call so you have the parent id at the end. Otherwise, call the function itself with the children of the current level. I hope you get the idea behind this. If you don't know how recursive functions work just google it and learn them.

about 4 years ago · Juan Pablo Isaza Relatório

0

What I would do is to use recursion to go through each nested object and check if there is some children with the key you are looking

function getParentKey(arr, key, index = 0) {
      
  if (!Array.isArray(arr[index].Children)) return;

  if (arr[index].Children.some(child => child.Key === key))
    return arr[index].Key;

  return getParentKey(arr[index], key, index + 1);
}

console.log(getParentKey(mydata, "10"));

Here a working example

const mydata = [{
  "Name": "Main Menu",
  "Key": "1",
  "Children": [{
    "Name": "Sub Menu 1",
    "Key": "10",
    "Children": [{
      "Name": "Very Sub Menu",
      "Key": "20",
      "Children": []
    }]
  }]
}, {
  "Name": "Main Menu 2",
  "Key": "2",
  "Children": [{
    "Name": "Sub Menu 2",
    "Key": "11",
    "Children": [{
      "Name": "Very Sub Menu 2",
      "Key": "21",
      "Children": [{
        "Name": "Extra Small Menu",
        "Key": "30",
        "Children": []
      }]
    }]
  }]
}]

function getParentKey(arr, key, index = 0) {
  
  if (!Array.isArray(arr[index].Children)) return;

  if (arr[index].Children.some(child => child.Key === key))
    return arr[index].Key;

  return getParentKey(arr[index], key, index + 1);
}

console.log(getParentKey(mydata, "10"));

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