1

I have an array like this:

[
  {id: 32, color: 'ff00dd'},
  {id: 64, color: 'ab230b'},
  {id: 102, color: '5f561d'}
]

How can I convert it to this format:

{ 32: 'ff00dd', 64: 'ab230b', 102: '5f561d'}

(LoDash is useable)

Thanks in advance!

1
  • Might I ask why you are tending towards that? Commented Oct 21, 2014 at 11:25

3 Answers 3

3

Without LoDash, a simple for loop can do this for us:

var data = [
    {id: 32, color: 'ff00dd'},
    {id: 64, color: 'ab230b'},
    {id: 102, color: '5f561d'}
  ],
  obj = {};

for (var i = 0; i < data.length; i++)
    obj[data[i].id] = data[i].color;

console.log(obj);
Open your JavaScript console to see the result.

The output of the console logging in the above snippet is:

> Object {32: "ff00dd", 64: "ab230b", 102: "5f561d"} 
Sign up to request clarification or add additional context in comments.

Comments

2

Using lodash:

_.zipObject(_.pluck(a, 'id'), _.pluck(a, 'color'));

Comments

1

You can just loop through the objects in your array and then add each as a property on a new object:

var data = [
  {id: 32, color: 'ff00dd'},
  {id: 64, color: 'ab230b'},
  {id: 102, color: '5f561d'}
];
var newObject = {};

_(data).forEach(function(obj) {
    newObject[obj.id] = obj.color;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.