I know that there are quite a lot of "Merge two arrays of objects in JS" questions, and I've read most of them. a few most similar to what I'm trying to do are:
How can I merge properties of two JavaScript objects dynamically?
Native javascript - merge two arrays of objects
How to merge two array of objects SQL style JOIN on JSON data
My issue is different because I'm trying to do a full SQL join, where the arrays will be different sizes, and will have new columns.
For example:
JSON1 = [{Color:"Blue", ID:"15", Size:"Large",Shape:"Square"},
{Color:"Red", ID:"9", Size:"Medium",Shape:"Circle"},
{Color:"Red", ID:"2", Size:"Large",Shape:"Triangle"},
{Color:"Yellow", ID:"3", Size:"Small",Shape:"Square"}];
JSON2 = [{Color:"Blue", Name:"Henry", Inches:"51"},
{Color:"Red", Name:"Jane", Inches:"7"},
{Color:"Pink", Name:"Jack", Inches:"14"}];
Desired Output:
OUTPUT =[{Color:"Blue", ID:"15", Size:"Large",Shape:"Square",Name:"Henry", Inches:"51"},
{Color:"Red", ID:"9", Size:"Medium",Shape:"Circle",Name:"Jane", Inches:"7"},
{Color:"Red", ID:"2", Size:"Large",Shape:"Triangle",Name:"Jane", Inches:"7"},
{Color:"Yellow", ID:"3", Size:"Small",Shape:"Square",Name:null, Inches:null},
{Color:"Pink", ID:null, Size:null,Shape:null,Name:"Jack", Inches:"14"}];
So, similar to a full SQL join, I want the output JSON to contain all columns, matched when there is a match, but a new row if a key:value pair in the second JSON doesn't match any of the ones in any of the objects in the first.
What I have so far is below. It generally works but has a couple issues. I'm merging on a specific pre-defined value, and it would be nice for the function to figure out where the matching value was. Also, my function fails if I add more than one new property column to JSON2(i.e. it works if JSON2 has Color and Inches, but not Color, Inches, and Name.) Because I'm just hashing one property to one other.
var hash={};
for(var e in JSON2){
hash[JSON2[e]["Color"]]= JSON2[e]["Inches"];
}
var trackHash = hash;
for(var k in JSON1){
JSON1[k]["Inches"] = hash[JSON1[k]["Color"]];
if(hash[JSON1[k]["Color"]]===undefined){
delete trackHash[JSON1[k]["Color"]];
}
}
for(var obj in JSON2){
if(trackHash[JSON2[obj]["Color"]]!==undefined){
JSON1.push(JSON2[obj]);
}
}