Skip to content
Advertisement

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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement