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"
}
This question is related to
javascript
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" }
Trying to fix this answer in How do I convert array of Objects into one Object in JavaScript?,
this should do it:
var array = [_x000D_
{key:'k1',value:'v1'},_x000D_
{key:'k2',value:'v2'},_x000D_
{key:'k3',value:'v3'}_x000D_
];_x000D_
var mapped = array .map(item => ({ [item.key]: item.value }) );_x000D_
var newObj = Object.assign({}, ...mapped );_x000D_
console.log(newObj );
_x000D_
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));
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).
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'));
// original_x000D_
var arr = [{_x000D_
key: '11',_x000D_
value: '1100',_x000D_
$$hashKey: '00X'_x000D_
},_x000D_
{_x000D_
key: '22',_x000D_
value: '2200',_x000D_
$$hashKey: '018'_x000D_
}_x000D_
];_x000D_
_x000D_
// My solution_x000D_
var obj = {};_x000D_
for (let i = 0; i < arr.length; i++) {_x000D_
obj[arr[i].key] = arr[i].value;_x000D_
}_x000D_
console.log(obj)
_x000D_
Using Object.fromEntries:
const array = [_x000D_
{ key: "key1", value: "value1" },_x000D_
{ key: "key2", value: "value2" },_x000D_
];_x000D_
_x000D_
const obj = Object.fromEntries(array.map(item => [item.key, item.value]));_x000D_
_x000D_
console.log(obj);
_x000D_
Use lodash!
const obj = _.keyBy(arrayOfObjects, 'keyName')
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' } }
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
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"}
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.
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)
_x000D_
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.
Source: Stackoverflow.com