How do I convert array of Objects into one Object in JavaScript?
Asked Answered
W

18

242

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"
}
Waddington answered 9/11, 2013 at 9:44 Comment(2)
[{key:"11", value:"1100"}, {key:"22", value:"2200"}].reduce(function(m,v){m[v.key] = v.value; return m;}, {})Pill
If you’re looking for the inverse of this: Convert object to array of key–value objects like { name: "Apple", value: "0.6" }. 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?.Ligniform
D
80

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);
Dangle answered 9/11, 2013 at 9:55 Comment(0)
T
334

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.

Tendril answered 2/6, 2017 at 9:14 Comment(7)
Loved the one! var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});Bailee
is this one line faster or the conventional loop?Persuasion
@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-jsHopehopeful
You forgot to spread second object ({...obj, ...{[item.key]: item.value}}) ,{});Throughway
Thanks, wrapping this in an object actually is not required. I have fixed it.Tendril
This should be var object = arr.reduce((obj, item) => { obj[item.key] = item.value; return obj} ,{});Birkle
is that also 99% faster than Object.assign? Or just 99% faster than spread?Tallu
B
127

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 }) )));
Berneicebernelle answered 13/3, 2018 at 3:2 Comment(0)
D
80

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);
Dangle answered 9/11, 2013 at 9:55 Comment(0)
K
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/

Khosrow answered 13/5, 2016 at 17:10 Comment(3)
and if the key is dynamic?Philips
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; }Khosrow
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; },{});Khosrow
A
55

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);
Ardenardency answered 18/4, 2019 at 13:35 Comment(2)
This is cleaner and easier to read than the Array.map solutions imoObovoid
This is the cleanest way to do it IMHO, deserves more upvotes!Putsch
T
20

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

const obj = Object.assign({}, ...array);
Tainataint answered 18/5, 2021 at 10:42 Comment(1)
this only works if the objects in the array have different keys, as such this will only keep the last object AFAICT.Trying
R
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" }
Rooney answered 9/10, 2018 at 11:11 Comment(0)
S
14

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);
Sneak answered 30/11, 2022 at 8:9 Comment(0)
T
13

Use lodash!

const obj = _.keyBy(arrayOfObjects, 'keyName')
Tocantins answered 5/6, 2016 at 13:16 Comment(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();Kanishakanji
M
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"}
Masinissa answered 9/11, 2013 at 10:0 Comment(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.Masinissa
C
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'));
Cosmo answered 24/5, 2016 at 3:52 Comment(0)
I
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'}
Impala answered 8/12, 2021 at 15:18 Comment(0)
P
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);
Primrose answered 11/3, 2022 at 7:32 Comment(2)
let arr = array.map((event) => ({ [event.key]: event.value })); is enough. Not sure what advantage this answer offers over existing answers though?Patentee
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"}]Suggestible
L
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
}, {});
Lavenialaver answered 22/12, 2022 at 9:2 Comment(0)
P
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);
Papyrus answered 17/5, 2023 at 19:9 Comment(0)
F
-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/

Fultz answered 9/11, 2013 at 10:14 Comment(0)
A
-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)
Altogether answered 4/7, 2018 at 13:39 Comment(2)
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.Khmer
surely will keep in mind.Primrose
I
-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' } }
Isolecithal answered 25/8, 2019 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.