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"
}
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.
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 }) )));
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);
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/
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);
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" }
you can merge array of objects in to one object in one line:
const obj = Object.assign({}, ...array);
Use lodash!
const obj = _.keyBy(arrayOfObjects, 'keyName')
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"}
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);
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'));
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'}
let array = [
{ key: "key1", value: "value1" },
{ key: "key2", value: "value2" },
];
let arr = {};
arr = array.map((event) => ({ ...arr, [event.key]: event.value }));
console.log(arr);
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
}, {});
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/
// 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)
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' } }
Related
i'm trying to duplicate objects based on two properties that have multiple values differentiated by a comma.
For example:
I have an object
const obj = {
id: 1
date: "2021"
tst1: "111, 222"
tst2: "AAA, BBB"
}
And I would like the result to be an array of 2 objects in this case (because there are 2 values in tst1 OR tst2, these 2 properties will always have the same nr of values differentiated by a comma)
[{
id: 1,
date: "2021",
tst1: "111",
tst2: "AAA",
},
{
id: 1,
date: "2021",
tst1: "222",
tst2: "BBB",
}]
What I tried is this:
I created a temporary object
const tempObject = {
id: obj.id,
date: obj.date,
}
And then I would split and map the property that has multiple values, like this:
cont newObj = obj.tst1.split(",").map(function(value) {
let finalObj = {}
return finalObj = {
id: tempObject.id,
date: tempObject.date,
tst1: value,
})
And now, the newObj is an array of objects and each object contains a value of tst1.
The problem is I still have to do the same for the tst2...
And I was wondering if there is a simpler method to do this...
Thank you!
Here is an example that accepts an array of duplicate keys to differentiate. It first maps them to arrays of entries by splitting on ',' and then trimming the entries, then zips them by index to create sub-arrays of each specified property, finally it returns a result of the original object spread against an Object.fromEntries of the zipped properties.
const mapDuplicateProps = (obj, props) => {
const splitProps = props.map((p) =>
obj[p].split(',').map((s) => [p, s.trim()])
);
// [ [[ 'tst1', '111' ], [ 'tst1', '222' ]], [[ 'tst2', 'AAA' ], [ 'tst2', 'BBB' ]] ]
const dupeEntries = splitProps[0].map((_, i) => splitProps.map((p) => p[i]));
// [ [[ 'tst1', '111' ], [ 'tst2', 'AAA' ]], [[ 'tst1', '222' ], [ 'tst2', 'BBB' ]] ]
return dupeEntries.map((d) => ({ ...obj, ...Object.fromEntries(d) }));
};
const obj = {
id: 1,
date: '2021',
tst1: '111, 222',
tst2: 'AAA, BBB',
};
console.log(mapDuplicateProps(obj, ['tst1', 'tst2']));
Not sure if that's what you're searching for, but I tried making a more general use of what you try to do:
const duplicateProperties = obj => {
const properties = Object.entries(obj);
let acc = [{}];
properties.forEach(([key, value]) => {
if (typeof value === 'string' && value.includes(',')) {
const values = value.split(',');
values.forEach((v, i) => {
if (!acc[i]) {
acc[i] = {};
}
acc[i][key] = v.trim();
});
} else {
acc.forEach(o => o[key] = value);
}
});
return acc;
};
const obj = {
id: 1,
date: '2021',
tst1: '111, 222',
tst2: 'AAA, BBB',
};
console.log(duplicateProperties(obj));
You could start by determining the length of the result using Math.max(), String.split() etc.
Then you'd create an Array using Array.from(), returning the correct object for each value of the output index.
const obj = {
id: 1,
date: "2021",
tst1: "111, 222",
tst2: "AAA, BBB",
}
// Determine the length of our output array...
const length = Math.max(...Object.values(obj).map(s => (s + '').split(',').length))
// Map the object using the relevant index...
const result = Array.from({ length }, (_, idx) => {
return Object.fromEntries(Object.entries(obj).map(([key, value]) => {
const a = (value + '').split(/,\s*/);
return [key, a.length > 1 ? a[idx] : value ]
}))
})
console.log(result)
.as-console-wrapper { max-height: 100% !important; }
Just looking for the cleanest way to turn the following array into the following object format. Thanks a lot
const item = [
{ address: '123 fake street' },
{ loan: 'no' },
{ property: 'no' }
]
const obj = {
address: '123 fake street',
loan: 'no',
property: 'no'
}
You can use Object.assign() and spread syntax to convert the array of objects into a single object.
const item = [
{ address: '123 fake street' },
{ loan: 'no' },
{ property: 'no' }
]
const obj = Object.assign({}, ...item);
console.log(obj);
Reduce and spread syntax would be one clean way to convert the array to an object.
const item = [
{ address: '123 fake street' },
{ loan: 'no' },
{ property: 'no' }
]
let obj = item.reduce((pre, cur)=>{
return {...pre, ...cur};
}, {});
// Result: obj={address: '123 fake street', loan: 'no', property: 'no'}
Just use a simple for...of loop to iterate over the array, and Object.entries to extract the key/value. Then just update an empty object with that information
const item = [
{ address: '123 fake street' },
{ loan: 'no' },
{ property: 'no' }
];
const obj = {};
for (const el of item) {
const [[key, value]] = Object.entries(el);
obj[key] = value;
}
console.log(obj);
Additional documentation
Destructuring assignment
const arr = [{key:"address", value:"123 fake street"},{key:"loan", value:"no"},{key:"property", value:"no"}];
const object = arr.reduce(
(obj, item) => Object.assign(obj, { [item.key]: item.value }), {});
console.log(object)
One more solution which is 99% faster (jsperf tested)
const object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
and More simplest solution
// original
const arr = [
{key:"address", value:"123 fake street"},
{key:"loan", value:"no"},
{key:"property", value:"no"}
];
//convert
const result = {};
for (var i = 0; i < arr.length; i++) {
result[arr[i].key] = arr[i].value;
}
console.log(result);
I have an array object with following data:
const arr = [
{
key: 'mykey1597855209',
integrity: 'sha512-T9JWj=='
},
{
key: 'mykey159785520915978552101597855212',
integrity: 'sha512-T9JWj=='
},
{
key: 'mykey15978552091597855210',
integrity: 'sha512-lcddfd=='
},
{
key: 'otherkey15978552091597855210',
integrity: 'sha512-abcdfd=='
}];
I want to create key value pair from the the arr[] object such that integrity becomes key and the key becomes value
Desired Output is something like below:
{
"sha512-T9JWj==": [
"mykey1597855209",
"mykey159785520915978552101597855212"
],
"sha512-lcddfd==": [
"mykey15978552091597855210"
],
"sha512-abcdfd==": [
"otherkey15978552091597855210"
]
}
I have written following code:
const arr = [{
key: 'mykey1597855209',
integrity: 'sha512-T9JWj=='
},
{
key: 'mykey159785520915978552101597855212',
integrity: 'sha512-T9JWj=='
},
{
key: 'mykey15978552091597855210',
integrity: 'sha512-lcddfd=='
},
{
key: 'otherkey15978552091597855210',
integrity: 'sha512-abcdfd=='
}
];
const result = Object.assign(...arr.map(a => ({
[a.integrity]: a.key
})));
console.log(result)
You can use Object.fromEntries:
const arr = [{key: 'mykey1597855209',integrity: 'sha512-T9JWj=='},{key: 'mykey159785520915978552101597855212',integrity: 'sha512-T9JWj=='},{key: 'mykey15978552091597855210',integrity: 'sha512-lcddfd=='},{key: 'otherkey15978552091597855210',integrity: 'sha512-abcdfd=='}];
let map = Object.fromEntries(arr.map(({_, integrity }) => [integrity, []]));
arr.forEach(({key, integrity}) => map[integrity].push(key));
console.log(map);
Or reduce:
const arr = [{key: 'mykey1597855209',integrity: 'sha512-T9JWj=='},{key: 'mykey159785520915978552101597855212',integrity: 'sha512-T9JWj=='},{key: 'mykey15978552091597855210',integrity: 'sha512-lcddfd=='},{key: 'otherkey15978552091597855210',integrity: 'sha512-abcdfd=='}];
let map = arr.reduce((acc, { key, integrity }) => {
acc[integrity] = acc[integrity] || [];
acc[integrity].push(key);
return acc;
}, {});
console.log(map);
You can transform it like this:
let map = {};
arr.forEach({ key, integrity } => map[integrity] = key);
arr.reduce((acc, curr) => {
acc[curr.integrity] = (acc[curr.integrity]) ?
[ ...acc[curr.integrity], curr.key ] :
[ curr.key ]
return acc;
}, {})
I have an example:
var A = [{
key: "iphone",
value: "American"
}, {
key: "sony",
value: "Japan"
}]
I want to do this action:
B=[{value:"American"},{value:"Japan"}]
How can I do this? Help me.
Use Array.map and return a new Object with the value field,
DEMO
var A =[{key:"iphone",value:"American"},{key:"sony",value:"Japan"}] ;
var result = A.map(d => ({ value: d.value }));
console.log(result);
var B = A.map(function(obj) { return { value: obj.value }; });
or
var B = A.map(obj => ({ value: obj.value }));
Maybe you prefer this more readable syntax?
function myObjectConverter (inputObject) {
var outputObject = {};
// ignore the key property
outputObject.Country1 = inputObject.value1;
outputObject.Country2 = inputObject.value2;
outputObject.Country3 = inputObject.value3;
outputObject.Country4 = inputObject.value4;
// transfer any other items with new names
return outputObject;
}
var B = A.map(myObjectConverter);
I have one array of object.
Objs[0] = {Name : "ABC"};
Objs[1] = {Roll : 123}
I want to merge both, It will be like
Objs {
Name : "ABC",
Roll : 123
}
Any way to I achieve this?
You can use Object.assign method.
var Objs = [{
Name: "ABC"
}, {
Roll: 123
}];
console.log(
Object.assign.apply(null, [{}].concat(Objs))
)
Or you can use spread syntax instead of Function#apply method.
var Objs = [{
Name: "ABC"
}, {
Roll: 123
}];
console.log(
Object.assign({}, ...Objs)
)
You can try below code.
var jsonObj = {};
$.each(Objs, function(index) {
$.each(Objs[index], function(key, value) {
jsonObj[key] = value;
});
});