How to merge an array of object - javascript

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

Related

Create object from multiple object with same value in map JS [duplicate]

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

how to iterate through array object and check the parameter matches in javascript

I would like to know how to iterate through array of objects and return name in javascript.
I have array object obj in which based on type , return name.
var obj=[
{name: "suzuki", type: "vehicle"},
{name: "home", type: "land"}
]
var result = obj.forEach(e => {
if(Object.key(e) === 'vehicle'){
return e;
}
});
Expected Output
suzuki
With the same code you've used:
var obj = [
{ name: 'suzuki', type: 'vehicle' },
{ name: 'home', type: 'land' }
];
var vehicleArray = [];
obj.forEach(e => {
if (e.type === 'vehicle') {
console.log(e.name); # suzuki;
vehicleArray.push(e.name);
}
});
console.log(vehicleArray);
Live Preview
FYI
In case if you need to push those into an array use push("")
Objects can be accessed via dot(e.type) notation
You can use filter to filter the array (type 'vehicle' in your case) and then use map to get the names only.
var obj = [{
name: "suzuki",
type: "vehicle"
},
{
name: "home",
type: "land"
}
]
var result = obj
.filter(e => e.type === 'vehicle')
.map(e => e.name);
console.log(result);
You can make use of flatMap:
const obj=[{name: "suzuki", type: "vehicle"},{name: "home", type: "land"},{name: "car", type: "vehicle"}];
const carNames = obj.flatMap(o=>o.type=='vehicle' ? o.name : []);
console.log(carNames);

How to get into an object that is in an array

Let's say I have an array like this :
arrayOfObject = [{item: {this: is, that: is}}, {item2: {this: is, that: is}}]
I'm trying to access item and item2 without having to use a 0/1 index. I'd like to be able to say arrayOfObjects[item] to get into the object. Is this possible?
You can use Array.find.
arrayOfObject = [{
item: {
this: 'is',
that: 'is'
}
}, {
item2: {
this: 'is',
that: 'is'
}
}]
console.log(arrayOfObject.find(ob => ob['item']));
console.log(arrayOfObject.find(ob => ob['item2']));
var arrayOfObject = [{
"item": {
"this": "is",
"that": "is"
}
}, {
"item2": {
"this": "is",
"that": "is"
}
}];
var itemObject = {};
arrayOfObject.forEach(function(value) {
var filterObject = Object.keys(value).filter(val => val.indexOf("item") != -1);
if (filterObject.length > 0) {
filterObject.forEach(key => {
itemObject[key] = itemObject[key] || [];
itemObject[key].push(value[filterObject[0]]);
});
}
});
console.log(itemObject.item); //item
console.log(itemObject.item2); //item
You can not do exactly this but something similar where you would "convert" your array to an object and then use the keys to access the values:
arrayOfObject = [{ item: { this: "a", that: "b" } }, { item2: { this: "c", that: "d" } }]
const arrayToObject = arrayOfObject.reduce((r,c) => Object.assign(r,c), {})
console.log(arrayToObject['item'])
console.log(arrayToObject['item2'])
In the snippet above we convert the arrayOfObject to arrayToObject and then simply access the values via the keys.
Otherwise what you are trying to do is not possible since you can only access values from an array by index or via some kind of a function which would traverse it and get you the entry, like find etc.
Yeah sure it is possible:
var result = arrayOfObject.map(a => a.item);
or
var result = arrayOfObject.map(a => a.item2);

formatting dynamic json array

I have an json array as follows:
Maindata=[
{"name":"string1"},
{"name":"string2"},
{"name":"string3"}
];
what I need is an array of following type:
data=[
{
"name":"string1",
"name":"string2",
"name":"string3"
}
];
can anybody help me with some methods to obtain required json from original array.
(note: maindata is json array formed dynamically thats why its structure is like that)
Thanks in advance
You could use Object.assign and spread the array elements.
var array = [{ name1: "string1" }, { name2: "string2" }, { name3: "string3" }],
object = Object.assign({}, ...array);
console.log(object);
With reduce, you can do like following
var Maindata = [{
"name1": "string"
}, {
"name2": "string"
}, {
"name3": "string"
}];
var finalObj = Maindata.reduce((acc, cur) => {
Object.assign(acc, cur);
return acc;
}, {})
console.log(finalObj);
You can use Array.forEach or Array.reduce to iterate though the items of the Maindata object and for each item you can iterate through its keys(using Object.keys) and group the data into a new structure.(See the below snippet)
Solution using Array.forEach
var Maindata=[
{"name1":"string1"},
{"name2":"string2"},
{"name3":"string3"}
];
var result = {};
var newMaindata=[];
Maindata.forEach(function(el){
Object.keys(el).forEach(function(key){
result[key]=el[key];
});
});
newMaindata.push(result);
console.log(newMaindata);
Solution using Array.reduce
var Maindata = [{
"name1": "string1"
}, {
"name2": "string2"
}, {
"name3": "string3"
}];
var result ;
var newMaindata = [];
result = Maindata.reduce(function(acc,el) {
Object.keys(el).forEach(function(key) {
acc[key] = el[key];
});
return acc;
},{});
newMaindata.push(result);
console.log(newMaindata);

Get parent array key in deep nested object using lodash

I'm using Lodash JavaScript library in my project and have a problem in getting the parent array key object filtered object:
I've the following data:
var data = {
5: [{
id: "3",
label: "Manish"
}, {
id: "6",
label: "Rahul"
}, {
id: "7",
label: "Vikash"
}],
8: [{
id: "16",
label: "Pankaj"
}, {
id: "45",
label: "Akash"
}],
9: [{
id: "15",
label: "Sunil"
}]
}
My requirement is if I've the array of [6,16] then I want a new result array containing values 5,8 because these two array keys have objects which contain id:"6" and id:"16"
I tried it using _.flatten and _.pick method but could not work. I used the following code;
var list = [];
_.each(data, function(item){
list.push(_.omit(item, 'id'));
list.push(_.flatten(_.pick(item, 'id')));
});
var result = _.flatten(list);
console.log(result);
var res = _([6, 16]).map(function(id){
return _.findKey(data, function(arr){
return _.some(arr, {id: new String(id)});
})
}).compact().uniq().value();
If simple javascript solution is okay with you then
var searchId=[6,16];
var newArr = [];
for ( key in data ){
data[key].forEach( function(innerValue){
if ( searchId.indexOf( Number(innerValue.id) ) != -1 ) newArr.push( key );
} );
}
console.log(newArr);
try this:
( hope im not missing some syntax )
var result = [];
var filterArray = [6,16];
_.each(filterArray, function(item){
_.merge(result,_.filter(data, function(o) { return _.contains(o,{id:item}) }));
});
Using _.pickBy this problem is solved simply:
var myArr = [6, 16]
var res = _.pickBy(data, function (value) {
return _(value).map('id').map(_.toNumber).intersection(myArr).size();
});
console.log(res)
https://jsfiddle.net/7s4s7h3w/

Categories