172

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"
}
Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
Vijay Chouhan
  • 4,093
  • 5
  • 27
  • 34
  • 6
    `[{key:"11", value:"1100"}, {key:"22", value:"2200"}].reduce(function(m,v){m[v.key] = v.value; return m;}, {})` – david Nov 09 '13 at 09:57
  • 1
    If you’re looking for the inverse of this: [Convert object to array of key–value objects like `{ name: "Apple", value: "0.6" }`](/q/47863275/4642212). If you’re looking for a variant where the result is another array of individual objects with a single property (e.g. `[ { "11": "1100" }, { "22": "2200" } ]`), see [How to convert array of key–value objects to array of objects with a single property?](/q/34744208/4642212). – Sebastian Simon Dec 01 '21 at 01:37

16 Answers16

255

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.

Shevchenko Viktor
  • 4,350
  • 2
  • 16
  • 25
84

Trying to fix this answer in How do I convert array of Objects into one Object in JavaScript?,

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 }) )));
georgeawg
  • 47,985
  • 13
  • 70
  • 91
FirstOne
  • 5,463
  • 5
  • 25
  • 45
  • 1
    Thanks a lot! This should be the accepted answer in 2021. Maybe @vijay-chouhan can accept it. – arcety Aug 03 '21 at 07:59
74

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);
adiga
  • 31,610
  • 8
  • 53
  • 74
Tibos
  • 26,984
  • 4
  • 46
  • 61
  • 7
    Check out [FirstOne's answer](https://stackoverflow.com/a/49247635/1669279) for a modern approach. – Tibos Feb 10 '19 at 13:14
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/

jmarceli
  • 17,506
  • 5
  • 63
  • 63
GreQ
  • 961
  • 1
  • 8
  • 5
  • 3
    and if the key is dynamic? – Stefano Saitta Jun 02 '16 at 10:45
  • 1
    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; } – GreQ Jun 24 '16 at 07:33
  • 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; },{}); – GreQ Jun 24 '16 at 07:48
36

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);
Brage
  • 531
  • 5
  • 11
17

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" }
Hedley Smith
  • 1,181
  • 13
  • 12
12

Use lodash!

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

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

const obj = Object.assign({}, ...array);
B001ᛦ
  • 2,083
  • 6
  • 22
  • 31
Hisham
  • 1,105
  • 1
  • 16
  • 22
9

Based on answers suggested by many authors, I created a JsPref test scenario. https://jsperf.com/array2object82364

Below are the screenshots of performance. It is a little shocking to me to see, chrome result is in contrast to firefox and edge, even after running it several times.

Edge

Firefox

Chrome

Adarsh Madrecha
  • 4,677
  • 9
  • 61
  • 96
5

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

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"}
pstadler
  • 1,602
  • 1
  • 13
  • 23
  • 1
    Because that's how you solve this problem. About the naming for example: `array` is a reserved keyword so people use `arr` instead. etc. – pstadler Nov 09 '13 at 10:36
2

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'));
Paul
  • 19,097
  • 13
  • 76
  • 95
1

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'}
sAyEd
  • 33
  • 8
1
let array = [
  { key: "key1", value: "value1" },
  { key: "key2", value: "value2" },
];

let arr = {};

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

console.log(arr);
  • 1
    `let arr = array.map((event) => ({ [event.key]: event.value }));` is enough. Not sure what advantage this answer offers over existing answers though? – General Grievance Mar 12 '22 at 20:33
0

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/

silicakes
  • 5,406
  • 2
  • 26
  • 35
0

// 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)
Roshana Pitigala
  • 7,945
  • 8
  • 47
  • 71
  • 1
    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](https://stackoverflow.com/help/how-to-answer) to know more. – Roshana Pitigala Jul 04 '18 at 18:23
  • surely will keep in mind. – Soniya Rana Mar 16 '22 at 08:24
0

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' } }
ThibaultV
  • 73
  • 1
  • 9