Vijay Chouhan
Vijay Chouhan

Reputation: 4893

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

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"
}

Upvotes: 249

Views: 360889

Answers (18)

Gopal Mishra
Gopal Mishra

Reputation: 1965

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

Upvotes: 0

AbdulmateenChitrali
AbdulmateenChitrali

Reputation: 399

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
}, {});

Upvotes: 0

spielbug
spielbug

Reputation: 1371

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

Upvotes: 16

pstadler
pstadler

Reputation: 2273

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"}

Upvotes: 4

FirstOne
FirstOne

Reputation: 6225

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

Upvotes: 132

Soniya Rana
Soniya Rana

Reputation: 134

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

let arr = {};

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

console.log(arr);

Upvotes: 0

sAyEd
sAyEd

Reputation: 31

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'}

Upvotes: 0

Hisham
Hisham

Reputation: 1316

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

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

Upvotes: 20

Shevchenko Viktor
Shevchenko Viktor

Reputation: 5416

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.

Upvotes: 343

ThibaultV
ThibaultV

Reputation: 81

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' } }

Upvotes: -1

Tibos
Tibos

Reputation: 27853

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

Upvotes: 82

Brage
Brage

Reputation: 759

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

Upvotes: 57

Hedley Smith
Hedley Smith

Reputation: 1417

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" }

Upvotes: 18

omermindivanli
omermindivanli

Reputation: 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)

Upvotes: -1

GreQ
GreQ

Reputation: 1009

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/

Upvotes: 65

Use lodash!

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

Upvotes: 13

Paul
Paul

Reputation: 20091

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

Upvotes: 1

silicakes
silicakes

Reputation: 6902

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/

Upvotes: -1

Related Questions