Home > Net >  Get object from array of objects depending on a specific property
Get object from array of objects depending on a specific property

Time:04-16

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

CodePudding user response:

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

CodePudding user response:

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

  • Related