'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



Solution 1:[1]

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

Solution 2:[2]

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'];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 theshininglemonade