1

How to do convert array of objects like this:

[
   { 
      display_name: "view_dashboard",
      value: 1
   },
   { 
      display_name: "view_user",
      value: 0
   }
]

to this:

{view_dashboard: 1, view_user: 0}

3 Answers 3

2

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}
Sign up to request clarification or add additional context in comments.

Comments

1

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>");

Comments

1

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>');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.