Merge Multiple Objects Inside the Same Array into One Object

Merge multiple objects inside the same array into one object

If your environment supports Object.assign, then you can do the same in a succinct way like this

const arrObj = [{a: 1, b: 2}, {c: 3, d: 4}, {e: 5, f: 6}];
console.log(arrObj.reduce(function(result, current) { return Object.assign(result, current);}, {}));
// If you prefer arrow functions, you can make it a one-liner ;-)console.log(arrObj.reduce(((r, c) => Object.assign(r, c)), {}));
// Thanks Spen from the comments. You can use the spread operator with assignconsole.log(Object.assign({}, ...arrObj));

Merge multiple objects inside an object under an array

const arrData = [ {x: {value: 1}, y: {value: 2}}, {z: {value: 3}}]

const res = arrData.map(e => // iterate over array
Object.keys(e) // iterate over keys in e (x, y, z)
.reduce((acc, key) => { // transform {key: object} into {key: value}
acc[key] = e[key].value // transform value object value into value
return acc // and merge the keys
}, {})
)

console.log(res)

Merge two objects in an array into one object in array

Here was the answer, So I create an empty array and then I push key values into one single object using the push method.

  let templates = [];
for (let i = 0; i < documents.body.length; i++) {
let slice = documents.body[i];
if (slice.slice_type === 'structure') {
templates.push({
styles: slice.primary,
headline: [],
ids: []
});
} else if (slice.slice_type === 'section') {
templates.push({
styles: [],
headline: slice.primary.headline,
ids: slice.items.map(item => item.templates.id)
});
}
}

Output

  templates = [
{
headline [],
ids: []
},
{
styles: [],
headline: [],
ids: []
}
]

Combine array of objects into a single object

You can do something, like

const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],

result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))

console.log(result)
.as-console-wrapper{min-height:100%;}

Merge / Combine object arrays into single object

Assuming your example was wrong, and it's actually like below (since what you put in isn't even valid), you can just use Object.values(obj).flat()

var obj = {
"0": [{
"category": "A",
"index": 0,
"property": "Name",
"value": "Bob"
}],
"1": [{
"category": "A",
"index": 1,
"property": "Name",
"value": "Jessica"
}]
}

console.log(Object.values(obj).flat())

Merging multiple objects into a single object in the mongodb aggregation

If clocked_in_at and clocked_out_at are strings we can use $toDate to first convert thes to dates (which will make ordering easier). If they are already dates we can skip this step.

Then we can $project each clocked in and clocked out times into an array of objects which contain the day and the value. $dateTrunc is used to convert clocked_in_at and clocked_out_at to days, then $unwind the newly created datetime field. Now we can $group by the day ("$datetime.day") and visitor_id` keeping the $min in time and $max out time per day. We can $project again to clean up object structure:

db.collection.aggregate([
// (Assuming strings not dates) Convert to DateTime
{
"$addFields": {
"clocked_in_at": {
"$toDate": "$clocked_in_at"
},
"clocked_out_at": {
"$toDate": "$clocked_out_at"
}
}
},
{
"$project": {
"s_id": "$s_id",
"visitor_id": "$visitor_id",
"datetime": [
{
"day": {
"$dateTrunc": {
"date": "$clocked_in_at",
"unit": "day"
}
},
"in": "$clocked_in_at"
},
{
"day": {
"$dateTrunc": {
"date": "$clocked_out_at",
"unit": "day"
}
},
"out": "$clocked_out_at"
}
]
}
},
{
"$unwind": "$datetime"
},
{
"$group": {
"_id": {
"visitor_id": "$visitor_id",
"day": "$datetime.day"
},
"s_id": {
"$first": "$s_id"
},
"clocked_in_at": {
"$min": "$datetime.in"
},
"clocked_out_at": {
"$max": "$datetime.out"
}
}
},
{
"$project": {
"_id": "$s_id",
"clocked_out_at": "$clocked_out_at",
"clocked_in_at": "$clocked_in_at",
"visitor_id": "$_id.visitor_id"
}
}
])
[
{
"_id": "6182552fde30e84900ba33fd",
"clocked_in_at": ISODate("2021-11-06T06:00:00Z"),
"clocked_out_at": ISODate("2021-11-06T13:00:00Z"),
"visitor_id": "6166c10965959d147c69aa90"
},
{
"_id": "618192d4654484639c47fa2d",
"clocked_in_at": ISODate("2021-11-05T03:00:00Z"),
"clocked_out_at": ISODate("2021-11-05T12:00:00Z"),
"visitor_id": "6166c10965959d147c69aa90"
},
{
"_id": "6182552fde30e84900ba33fd",
"clocked_in_at": ISODate("2021-11-05T04:00:00Z"),
"clocked_out_at": ISODate("2021-11-05T11:00:00Z"),
"visitor_id": "6182e4cea8b52121d01dff1b"
}
]

mongoplayground

Note _id was not unique in the provided sample so the field was modified to s_id:

[
{
"s_id": "618192d4654484639c47fa2d",
"clocked_out_at": "2021-11-05T10:00:00.000Z",
"clocked_in_at": "2021-11-05T03:00:00.000Z",
"visitor_id": "6166c10965959d147c69aa90"
},
{
"s_id": "6182552fde30e84900ba33fd",
"clocked_out_at": "2021-11-05T11:00:00.000Z",
"clocked_in_at": "2021-11-05T04:00:00.000Z",
"visitor_id": "6182e4cea8b52121d01dff1b"
},
{
"s_id": "6182552fde30e84900ba33fd",
"clocked_out_at": "2021-11-05T12:00:00.000Z",
"clocked_in_at": "2021-11-05T05:00:00.000Z",
"visitor_id": "6166c10965959d147c69aa90"
},
{
"s_id": "6182552fde30e84900ba33fd",
"clocked_out_at": "2021-11-06T13:00:00.000Z",
"clocked_in_at": "2021-11-06T06:00:00.000Z",
"visitor_id": "6166c10965959d147c69aa90"
}
]

This means that the initial $project will need to be updated to:

  {
"$project": {
"s_id": "$_id", // <- grab `_id` instead of `s_id`

Javascript merge multiple objects in an array

Something like this would work:

const myArr = [
{PersonIds: "6",TypeIds: "2",VekilIds: "6"},
{PersonIds: "4",TypeIds: "27",VekilIds: "11"},
];

const myObj = myArr.reduce((acc, cur, idx) => {
const newAcc = {...acc};
for (let [key, val] of Object.entries(cur)) {
if (!newAcc[key]) {
newAcc[key] = val;
} else {
newAcc[key] = `${newAcc[key]},${val}`;
}
}
return newAcc;
});

console.log(myObj);


Related Topics



Leave a reply



Submit