How to Merge Two Json Object Values by Id With Plain JavaScript (Es6)

How to merge two json object values by id with plain Javascript (ES6)

You could use Map and Object.assign for merging the objects.

var request1 = [{    ObjId: 174864,    ObjMutationD: "2010-07-09T00:00:00.000Z",    ObjMitarbeiterS: "epf",    ObjAufId: 142  }, {    ObjId: 175999,    ObjMutationD: "2010-07-09T00:00:00.000Z",    ObjMitarbeiterS: "epf",    ObjAufId: 149  }],  request2 = [{    ObjId: 174864,    MulPfadS: "M:\\Originalbilder\\FGS\\95nn",    MulDateiS: "9576.305-034-1",    MulExtentS: "jpg"  }, {    ObjId: 177791,    MulPfadS: "M:\\Originalbilder\\FGS\\95nn",    MulDateiS: "9576.305-035-1",    MulExtentS: "jpg"  }];
var result = [...[request1, request2].reduce((m, a) => (a.forEach(o => m.has(o.ObjId) && Object.assign(m.get(o.ObjId), o) || m.set(o.ObjId, o)), m), new Map).values()];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Combine 2 JSON objects of unequal size with ID

I figured that by using reduce I could make it work.

var finalResult = [...[json1, json2].reduce((m, a) => (a.forEach(o => m.has(o.id) && Object.assign(m.get(o.id), o) || m.set(o.id, o)), m), new Map).values()];

How can I merge properties of two JavaScript objects dynamically?

ECMAScript 2018 Standard Method

You would use object spread:

let merged = {...obj1, ...obj2};

merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1.

/** There's no limit to the number of objects you can merge.
* Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};

Here is also the MDN documentation for this syntax. If you're using babel you'll need the babel-plugin-transform-object-rest-spread plugin for it to work.

ECMAScript 2015 (ES6) Standard Method

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
* All objects get merged into the first object.
* Only the object in the first argument is mutated and returned.
* Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

(see MDN JavaScript Reference)


Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

Example function:

/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}

JavaScript merging objects by id

This should do the trick:

var mergedList = _.map(a1, function(item){
return _.extend(item, _.findWhere(a2, { id: item.id }));
});

This assumes that the id of the second object in a1 should be 2 rather than "2"

How to Combine Multiple Objects by id

An alternative is using the function reduce to group the objects by _id and the function Object.values to extract the grouped objects.

let arr = [   {      "_id": "591323037ca83d48eac1ff31",      "sessionStartTime": "2017-05-09T23:10:40.000Z",      "sessionEndTime": "2017-05-10T07:28:40.000Z",      "timeSessionMinutes": 212,    },    {      "_id": "591323037ca83d48eac1ff31",      "eventSummary": "Working",      "eventActivity": "Work",      "eventStart": "2017-05-09T10:00:00+02:00",      "eventEnd": "2017-05-09T17:00:00+02:00"    },    {      "_id": "5917165b3ffac25462193490",      "sessionStartTime": "2017-05-12T22:06:09.000Z",      "sessionEndTime": "2017-05-13T06:12:09.000Z",      "timeSessionMinutes": 322,    },    {      "_id": "5917165b3ffac25462193490",      "eventSummary": "Traveling back home",      "eventActivity": "Travel",      "eventStart": "2017-05-09T17:00:00+02:00",      "eventEnd": "2017-05-09T17:30:00+02:00"    }],    result = Object.values(arr.reduce((a, c) => {      Object.assign((a[c['_id']] || (a[c['_id']] = Object.create(null))), c);      return a;    }, Object.create(null)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to join two JavaScript arrays of JSON Objects, without using JQUERY?

After the blunder with misreading your question I spent a bit of time and built this example for you to merge the two arrays based on the Id.

let dataset = [{    "State": "AL",    "id": 1000,    "name": "Alabama",    "percent_educated": 24  },  {    "State": "AL",    "id": 1001,    "name": "Autauga County",    "percent_educated": 24.6  },  {    "State": "AL",    "id": 1003,    "name": "Baldwin County",    "percent_educated": 29.5  }];
let dataset2 = [{ "id": 1000, "qualified_professionals": "64,767,787", "high_school": "58,820,411", "middle_school_or_lower": "27,818,380" }, { "id": 1001, "qualified_professionals": "783,076", "high_school": "1,009,593", "middle_school_or_lower": "496,036" }, { "id": 1003, "qualified_professionals": "8,968", "high_school": "12,519", "middle_school_or_lower": "4,528" }];
// create a function to reduce your arrayslet reducer = function(accumulator, currentValue, currentIndex, array) { // check if the item already exists in the array let found = accumulator.find((item) => item.id == currentValue.id); if (found) { // if it exists then use assign to merge the two values Object.assign(found, currentValue) } else { // doesn't exist, just add it to the array accumulator.push(currentValue); } return accumulator;}
let datasetCombined = [];
dataset.reduce(reducer, datasetCombined);dataset2.reduce(reducer, datasetCombined);
console.log(datasetCombined);

Combine or merge JSON on node.js without jQuery

A normal loop?

function extend(target) {
var sources = [].slice.call(arguments, 1);
sources.forEach(function (source) {
for (var prop in source) {
target[prop] = source[prop];
}
});
return target;
}

var object3 = extend({}, object1, object2);

That's a basic starting point. You may want to add things like a hasOwnProperty check, or add some logic to handle the case where multiple source objects have a property with the same identifier.

Here's a working example.

Side note: what you are referring to as "JSON" are actually normal JavaScript objects. JSON is simply a text format that shares some syntax with JavaScript.



Related Topics



Leave a reply



Submit