251

I have an array of objects:

[ 
  { key : '11', value : '1100', $$hashKey : '00X' },
  { key : '22', value : '2200', $$hashKey : '018' }
];

How do I convert it into the following by JavaScript?

{
  "11": "1100",
  "22": "2200"
}
2

18 Answers 18

343

Tiny ES6 solution can look like:

var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}];
var object = arr.reduce(
  (obj, item) => Object.assign(obj, { [item.key]: item.value }), {});

console.log(object)

Also, if you use object spread, than it can look like:

var object = arr.reduce((obj, item) => ({...obj, [item.key]: item.value}) ,{});

One more solution that is 99% faster is(tested on jsperf):

var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});

Here we benefit from comma operator, it evaluates all expression before comma and returns a last one(after last comma). So we don't copy obj each time, rather assigning new property to it.

Sign up to request clarification or add additional context in comments.

8 Comments

Loved the one! var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
is this one line faster or the conventional loop?
@Jeb50, conventional loop is the fastest, but not by much over the comma operator. Object.assign/spread operator is an order of magnitude slower: jsperf.com/comma-operator-js
You forgot to spread second object ({...obj, ...{[item.key]: item.value}}) ,{});
This should be var object = arr.reduce((obj, item) => { obj[item.key] = item.value; return obj} ,{});
|
133

This should do it:

var array = [
    { key: 'k1', value: 'v1' },
    { key: 'k2', value: 'v2' },
    { key: 'k3', value: 'v3' }
];
var mapped = array.map(item => ({ [item.key]: item.value }) );
var newObj = Object.assign({}, ...mapped );
console.log(newObj );


One-liner:
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));

Comments

83

You're probably looking for something like this:

// original
var arr = [ 
  {key : '11', value : '1100', $$hashKey : '00X' },
  {key : '22', value : '2200', $$hashKey : '018' }
];

//convert
var result = {};
for (var i = 0; i < arr.length; i++) {
  result[arr[i].key] = arr[i].value;
}

console.log(result);

Comments

65

I like the functional approach to achieve this task:

var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
  obj[item.key] = item.value; 
  return obj;
}, {});

Note: Last {} is the initial obj value for reduce function, if you won't provide the initial value the first arr element will be used (which is probably undesirable).

https://jsfiddle.net/GreQ/2xa078da/

3 Comments

and if the key is dynamic?
Well, you should know which property of the given item/object should be used as key and which as value no? But if we assume that wfirst prop is always the key and second the value we could use a callback function like this: function(obj,item){ var keys = item.keys(); obj[item[keys[0]]] = item[keys[0]]; return obj; }
Correction of callback above: code var obj = arr.reduce(function(obj,item){ var keys = Object.keys(item); obj[item[keys[0]]] = item[keys[1]]; return obj; },{});
58

Using Object.fromEntries:

const array = [
    { key: "key1", value: "value1" },
    { key: "key2", value: "value2" },
];

const obj = Object.fromEntries(array.map(item => [item.key, item.value]));

console.log(obj);

2 Comments

This is cleaner and easier to read than the Array.map solutions imo
This is the cleanest way to do it IMHO, deserves more upvotes!
21

you can merge array of objects in to one object in one line:

const obj = Object.assign({}, ...array);

1 Comment

this only works if the objects in the array have different keys, as such this will only keep the last object AFAICT.
18

A clean way to do this using modern JavaScript is as follows:

const array = [
  { name: "something", value: "something" },
  { name: "somethingElse", value: "something else" },
];

const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));

// >> { something: "something", somethingElse: "something else" }

Comments

17

Simple way using reduce

// Input : 
const data = [{key: 'value'}, {otherKey: 'otherValue'}];

data.reduce((prev, curr) => ({...prev, ...curr}) , {});

// Output
{key: 'value', otherKey: 'otherValue'}

More simple Using Object.assign

Object.assign({}, ...array);

Comments

13

Use lodash!

const obj = _.keyBy(arrayOfObjects, 'keyName')

1 Comment

this would have resulted in: { 11:{ key : '11', value : '1100', $$hashKey : '00X' }, 22:{ key : '22', value : '2200', $$hashKey : '018' } } what u want to do instead is: const obj= _.chain(arrayOfObjects) .keyBy('keyName') .mapValues('value') .value();
4

Update: The world kept turning. Use a functional approach instead.


Previous answer

Here you go:

var arr = [{ key: "11", value: "1100" }, { key: "22", value: "2200" }];
var result = {};
for (var i=0, len=arr.length; i < len; i++) {
    result[arr[i].key] = arr[i].value;
}
console.log(result); // {11: "1000", 22: "2200"}

1 Comment

Because that's how you solve this problem. About the naming for example: array is a reserved keyword so people use arr instead. etc.
1

Using Underscore.js:

var myArray = [
  Object { key="11", value="1100", $$hashKey="00X"},
  Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));

Comments

0

Nearby 2022, I like this approach specially when the array of objects are dynamic which also suggested based on @AdarshMadrecha's test case scenario,

const array = [ 
  { key : '11', value : '1100', $$hashKey : '00X' },
  { key : '22', value : '2200', $$hashKey : '018' }];
  
let obj = {};
array.forEach( v => { obj[v.key] = v.value }) //assign to new object
console.log(obj) //{11: '1100', 22: '2200'}

Comments

0
let array = [
  { key: "key1", value: "value1" },
  { key: "key2", value: "value2" },
];

let arr = {};

arr = array.map((event) => ({ ...arr, [event.key]: event.value }));

console.log(arr);

2 Comments

let arr = array.map((event) => ({ [event.key]: event.value })); is enough. Not sure what advantage this answer offers over existing answers though?
This actually doesn't convert the array of objects to an object which is the question asked. This will return an array of objects with the key and value mapped out. [{"key1": "value1"},{"key2": "value2"}]
0

Was did yesterday

// Convert the task data or array to the object for use in the above form
 const {clientData} = taskData.reduce((obj, item) => {
 // Use the clientData (You can set your own key name) as the key and the 
 // entire item as the value
 obj['clientData'] = item
 return obj
}, {});

Comments

0

I see so many variations in the answers above. This is how I did it using reduce:

// original
var fields = [{
    fieldName: 'name',
    fieldValue: 'ABC',
    fieldType: 'string'
  },
  {
    fieldName: 'phone',
    fieldValue: '12345',
    fieldType: 'number'
  }
];

//convert
const result = fields.reduce((acc, field) => {
  acc[field.fieldName] = field.fieldValue;
  return acc;
}, {});

console.log(result);

Comments

-1

Here's how to dynamically accept the above as a string and interpolate it into an object:

var stringObject = '[Object { key="11", value="1100", $$hashKey="00X"}, Object { key="22", value="2200", $$hashKey="018"}]';

function interpolateStringObject(stringObject) {
  var jsObj = {};
  var processedObj = stringObject.split("[Object { ");
  processedObj = processedObj[1].split("},");
  $.each(processedObj, function (i, v) {
      jsObj[v.split("key=")[1].split(",")[0]] = v.split("value=")[1].split(",")[0].replace(/\"/g,'');
  });

  return jsObj
}

var t = interpolateStringObject(stringObject); //t is the object you want

http://jsfiddle.net/3QKmX/1/

Comments

-1

// original
var arr = [{
    key: '11',
    value: '1100',
    $$hashKey: '00X'
  },
  {
    key: '22',
    value: '2200',
    $$hashKey: '018'
  }
];

// My solution
var obj = {};
for (let i = 0; i < arr.length; i++) {
  obj[arr[i].key] = arr[i].value;
}
console.log(obj)

2 Comments

While this may answer the question it's better to add some description on how this answer may help to solve the issue. Please read How do I write a good answer to know more.
surely will keep in mind.
-1

You can use the mapKeys lodash function for that. Just one line of code!

Please refer to this complete code sample (copy paste this into repl.it or similar):

import _ from 'lodash';
// or commonjs:
// const _ = require('lodash');

let a = [{ id: 23, title: 'meat' }, { id: 45, title: 'fish' }, { id: 71, title: 'fruit' }]
let b = _.mapKeys(a, 'id');
console.log(b);
// b:
// { '23': { id: 23, title: 'meat' },
//   '45': { id: 45, title: 'fish' },
//   '71': { id: 71, title: 'fruit' } }

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.