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

191
Visualizações
Better way to access nested attributes in JavaScript

I have this function in which I want to access nested attributes from passed arguments inside the function.

var objectsArr = [
  {nestedobj:{property:'1'}},
  {nestedobj:{property:'3'}},
  {nestedobj:{property:'2'}},
  {nestedobj:{property:'4'}}
];

function sortObjectsArr(objectsArray) {
  if (arguments.length == 2) {
    objectsArray.sort((a,b) => a[arguments[1]] - b[arguments[1]]);
  }

  if (arguments.length == 3) {
    objectsArray.sort((a,b) => a[arguments[1]][arguments[2]] - b[arguments[1]][arguments[2]]);
  }

  if (arguments.length == 4) {
    objectsArray.sort((a,b) => a[arguments[1]][arguments[2]][arguments[3]] - b[arguments[1]][arguments[2]][arguments[3]]);
  }  
  //and so on and so forth
}


sortObjectsArr(objectsArr, 'nestedobj', 'property');

console.log(objectsArr);

Is there a nicer way to access the attributes from the object? rather than [arguments[1]][arguments[2]][arguments[3]].... ?

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

0

So I would first take the other args as a rest parameter instead of using the arguments array. Then i wold define a small helper function.

function sortObjectsArr(objectsArray, ...path) {
  objectsArray.sort((a, b) => getFromPath(a, path) - getFromPath(b, path))
}

function getFromPath(obj, path) {
  let r = obj;
  path.forEach(key => { r = r[key]})
  return r
}

let objectsArr = [
  {nestedobj:{property:'1'}},
  {nestedobj:{property:'3'}},
  {nestedobj:{property:'2'}},
  {nestedobj:{property:'4'}}
]; 

sortObjectsArr(objectsArr, 'nestedobj', 'property'); 
console.log(objectsArr);

Finally: avoid using var, use let instead, its old and behaves weirdly (in ways you wouldnt expect). But explaining that is outside of this answer, you can google it.

EDIT: if you want to be really cool you can use the reduce function:

function getFromPath(obj, path) {
     return path.reduce((o, key) => o[key], obj)
}

If this is more readable you need to decide for yourself.

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