Last Updated: February 25, 2016
·
320
· ashwinkumar

Map array of key/value pairs to a Javascript object

Want to convert this

var temp = [
  { 
    "name" : "apple", 
    "value" : "A for apple"
  },
  { 
    "name" : "ball", 
    "value" : "B for ball"
  }, 
  { 
    "name" : "cat", 
    "value" : "C for cat"
  }
]

to

{
  apple: "A for apple", 
  ball: "B for ball", 
  cat: "C for cat"
}

?

Here's how you can do it with underscores.js

temp = _.object(_.map(temp, function(x){return [x.name, x.value]}))

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside