How to do convert array of objects like this:
[
{
display_name: \"view_dashboard\",
value: 1
},
{
display_name: \"view_user\",
You could try using the reduce function:
var myArray =[
{
display_name: "view_dashboard",
value: 1
},
{
display_name: "view_user",
value: 0
}
]
var result = myArray.reduce(function(obj, item) {
obj[item.display_name] = item.value;
return obj;
}, {})
console.log(result); // {view_dashboard: 1, view_user: 0}
An approach with a Array#forEach
:
var array = [{ display_name: "view_dashboard", value: 1 }, { display_name: "view_user", value: 0 }],
object = {};
array.forEach(function (o) {
object[o.display_name] = o.value;
});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can try Array.map
var data = [{
display_name: "view_dashboard",
value: 1
}, {
display_name: "view_user",
value: 0
}];
var result = data.map(function(o){
var _tmp = {};
_tmp[o.display_name] = o.value
return _tmp;
});
document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>");