Suraz Khanal
Suraz Khanal

Reputation: 222

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?

Upvotes: 1

Views: 461

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386624

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

Upvotes: 2

Related Questions