Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!