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

190
Vistas
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 Respuestas
Responde la pregunta

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 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