-2

I have a JSON like below (which is basically constructed out of a Dictionary):

{ "test1":["a","b","c"], "test2":["c","d"], "test3":["f"] }

And I want to parse and format above like this:

[
    {
        "user": "test1",
        "cmd": ["a","b","c"]      
    }
    {
        "user": "test2",
        "cmd": ["c","d"]
    },
    {
        "user": "test3",
        "cmd": ["f"]
    }
]

Any suggestions on how to do this using JavaScript?

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326

2 Answers2

3

It's not clear from your question if your dictionary is a JS object or a JSON string. If it's JSON, you'll have to first parse it:

var dictionary = JSON.parse(theJSONstring);

then follow the instructions below.

If you're supporting IE8-, you'll have to polyfill JSON support.


var dictionary = {
    "test1": ["a","b","c"],
    "test2": ["c","d"],
    "test3": ["f"],
};

var commands = Object.keys(dictionary).map(function (key) {
    return { user: key, cmd: dictionary[key] };
});

If you're unfortunate enough that you have to support ancient browsers (IE8-), use this:

var dictionary = {
    "test1":["a","b","c"],
    "test2":["c","d"],
    "test3":["f"],
};

var commands = [];

for (var key in dictionary) {
    if (Object.prototype.hasOwnProperty.call(dictionary, key))
    {
        commands.push({ user: key, cmd: dictionary[key] });
    }
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
0

Maybe something like this:

var testObject = {
    "test1": ["a", "b", "c"],
        "test2": ["c", "d"],
        "test3": ["f"]
},
userArray = [];

for (test in testObject) {

    if (Object.prototype.hasOwnProperty.call(testObject, test)) {

        userArray.push({
            user: test,
            cmd: testObject[test]
        });

    }
}
Boyan Hristov
  • 1,067
  • 3
  • 15
  • 41