Eduardo Pliego Meré Eduardo Pliego Meré - 6 months ago 31
Node.js Question

How to convert JSON Array to JSON object?

I have a json array. I need to bring this:

[
{"id": ["1"],
"title": ["hello"],
"start": ["2016-05-20"],
"end": ["2016-05-25"],
}
]


to this:

[
{"id": "1",
"title: "hello",
"start": "2016-05-20",
"end": "2016-05-25",
}
]


How to do that?

Answer

You could loop with Array#forEach() and assign all properties with the first element.

var array = [{ "id": ["1"], "title": ["hello"], "start": ["2016-05-20"], "end": ["2016-05-25"], }];

array.forEach(function (a) {
    Object.keys(a).forEach(function (k) {
        a[k] = a[k][0];
    });
});

console.log(array);