How to Join Two JavaScript Objects, Without Using Jquery

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

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-proposal-object-rest-spread plugin for it to work (This plugin is included in @babel/preset-env, in ES2018).

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

Merge two objects without override

With ES2015 now being supported in all modern browsers, the native Object.assign can be used to extend objects

Object.assign({}, _default, values)

Object.assign

Note that default is a reserved keyword, and can't be used as a variable name


The original answer, written in 2013 :

Since this is tagged with jQuery, you could use $.extend for a simple cross-browser solution

var temp = {};
$.extend(true, temp, _default, values);
values = temp;

Concatenate two JSON objects without jQuery

Thanks all!

I was trying to create a conglomerated object of multiple objects to send as the overall object for a rest call from angular to a javaEE based API that had an object as a parameter as well as a dynamic variable for the REST url. I was under the assumption that the objects needed to not have a key in the json, but I was wrong.

So the object I send is basically now:

"dynamicID": "keyValue",
"object1":
{
"field1-1": 1,
"field1-2": 2,
"field1-3": 3,
"field1-4": "four",
"field1-5":
{
"field1-1-1": 5.1,
"field1-1-2": 5.2
}
},
"object2":
{
"field2-1": 21,
"field2-2": 22,
"field2-3": "three",
"field2-4":
{
"field2-1-1": 4.1,
"field2-1-2": 4.2
}
}

Which I did from simply creating a new object:

$scope.restObject = {"dynamicID": $scope.keyValue, $scope.object1, $scope.object2}

merge two objects without adding new properties

What about simple for loop:

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

For nested object you can wrap this code into recursive function:

function mergeObj(a, b) {
for (var key in b) {
if (key in a) {
a[key] = typeof a[key] === 'object' && typeof b[key] === 'object' ? mergeObj(a[key], b[key]) : b[key];
}
}
return a;
}

Demo: http://jsfiddle.net/rHUM6/

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.

Merging two objects in javascript without overwriting users progress in a game

Basically you need a recursive version of $.extend and Object.assign that recursively merges values of two objects. Fortunately, Lodash has such the function you need.

Check out lodash's merge. It enables you to overwrite values that are in the same key "path", or add on if they don't already exist in the first object.

For example:

var foo = {
a: {
b: 1
},
c: 2
}

var bar = {
a: {
b: 2
},
d: 3
}

console.log(_.merge(foo, bar)) =>

{
a: {
b: 2 // overwritten by value in bar
},
c: 2,
d: 3 // added by bar
}

Concatenate two JSON objects

Based on your description in the comments, you'd simply do an array concat:

var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);
// jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23},
//{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];


Related Topics



Leave a reply



Submit