246

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

339

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.

8
  • 6
    Loved the one! var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
    – Sohail
    Commented Aug 21, 2018 at 13:36
  • is this one line faster or the conventional loop?
    – Jeb50
    Commented Oct 5, 2019 at 19:33
  • 2
    @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 Commented Oct 7, 2019 at 20:09
  • 1
    You forgot to spread second object ({...obj, ...{[item.key]: item.value}}) ,{});
    – Julia
    Commented Jun 25, 2020 at 13:48
  • 3
    This should be var object = arr.reduce((obj, item) => { obj[item.key] = item.value; return obj} ,{});
    – kasvith
    Commented Jan 9, 2021 at 5:19
129

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 }) )));
0
81

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

0
64

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
  • 3
    and if the key is dynamic? Commented Jun 2, 2016 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
    Commented Jun 24, 2016 at 7: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
    Commented Jun 24, 2016 at 7:48
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
  • 1
    This is cleaner and easier to read than the Array.map solutions imo Commented Sep 9, 2021 at 3:36
  • This is the cleanest way to do it IMHO, deserves more upvotes! Commented Dec 29, 2022 at 8:37
20

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

const obj = Object.assign({}, ...array);
1
  • 1
    this only works if the objects in the array have different keys, as such this will only keep the last object AFAICT. Commented Oct 25, 2022 at 11:23
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" }
15

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

Use lodash!

const obj = _.keyBy(arrayOfObjects, 'keyName')
1
  • 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();
    – vilem cech
    Commented Apr 12, 2023 at 14:42
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
  • 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
    Commented Nov 9, 2013 at 10:36
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'));
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'}
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
  • 2
    let arr = array.map((event) => ({ [event.key]: event.value })); is enough. Not sure what advantage this answer offers over existing answers though? Commented Mar 12, 2022 at 20:33
  • 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"}] Commented Dec 7, 2022 at 4:00
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
}, {});
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);
-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/

-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
  • 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 to know more. Commented Jul 4, 2018 at 18:23
  • surely will keep in mind. Commented Mar 16, 2022 at 8:24
-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' } }

Not the answer you're looking for? Browse other questions tagged or ask your own question.