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

243
Views
Get object from array of objects depending on a specific property

Lets say we have the following:


let x = [
{"color": "blue", "cat": "eec" },
{"color": "red", "cat": "vbs" },
{"color": "black", "cat": "asd" },
]

how can I sort this by cat? so that I can then do something like

let y = sorted.asd.color;

or 

y = sorted[asd][color];

note: cat is unique

Thanks

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use .reduce:

let x = [
{"color": "blue", "cat": "eec" },
{"color": "red", "cat": "vbs" },
{"color": "black", "cat": "asd" },
]

const sorted = x.reduce((acc, el) => {
  acc[el.cat] = el;
  return acc;
}, {});

const y = sorted.asd.color;

console.log(y);

or .map and Object.entries:

let x = [
{"color": "blue", "cat": "eec" },
{"color": "red", "cat": "vbs" },
{"color": "black", "cat": "asd" },
]

const sorted = Object.fromEntries(x.map(el => [el.cat, el]));

const y = sorted.asd.color;

console.log(y);

about 4 years ago · Santiago Trujillo Report

0

You could try something like this:

const x = [
    {"color": "blue", "cat": "eec" },
    {"color": "red", "cat": "vbs" },
    {"color": "black", "cat": "asd" },
]

function sortByCat(array) {
    let cats = {};
    for (let i = 0; i < array.length; i++) {
        let currentObject = array[i];
        cats[currentObject.cat] = currentObject;
    }

    return cats;
}

let sorted = sortByCat(x);

let y = sorted.asd.color;
y = sorted['asd']['color'];

about 4 years ago · Santiago Trujillo 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!