Suraz Khanal Suraz Khanal - 1 month ago 8
Javascript Question

change object with angular foreach loop to array

This is my object
{angry: "ok", sad: "nw", fire: "ok", happy: "nw","something":"good"}

I want to change this object to something like this:

val[nw][0]="sad"
val[nw][1]="happy"
val[ok][0]="angry"
val[ok][1]="fire"
val[good][0]="something"


how can i do that?

Answer

You could iterate the keys and build a new object upon.

var object = { angry: "ok", sad: "nw", fire: "ok", happy: "nw", something: "good" },
    result = {};

Object.keys(object).forEach(function (k) {
    result[object[k]] = result[object[k]] || [];
    result[object[k]].push(k);
});

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