Suraz Khanal Suraz Khanal - 1 month ago 8
AngularJS Question

How to group object value by key in angularjs

I have an object with this structure

{aaas:"good","aasda":"ok","adasa":"good","ascas":"good","asdasd":"nw","asdasda":"nw",asdqw:"nw","assa":"ok","asscsa":"ok"}


Here I want to group each key with the similar value and put these to new object.
Just like
newObj={"aaas":"good","adasa":"good","ascas":"good"}

Answer

You could use an object and group by value.

var object = { aaas: "good", aasda: "ok", adasa: "good", ascas: "good", asdasd: "nw", asdasda: "nw", asdqw: "nw", assa: "ok", asscsa: "ok" },
    grouped = {};

Object.keys(object).forEach(function (k) {
    if (!grouped[object[k]]) {
        grouped[object[k]] = {};
    }
    grouped[object[k]][k] = object[k];
});

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments