Q: Merging multiple Array with subarrays based on key I'll explain first with an example as what I want to achieve.
I'll have a key called 'Code' as the merging parameter.
Example : 
var Items = [{'Item_Id':1,'Item_Name':'Soap','Code':001},[{'Item_Id':2,'Item_Name':'Powder','Code':002]

var ItemPrice = [{'ItemPrice_Id':1,'ItemPrice_ItemId':1,'Price':'10$','Code':001},[{'ItemPrice_Id':2,'ItemPrice_ItemId':2,'Price':'20$','Code':002]

var ItemFeatures = [{'FeatureId':2,'FeatureName':'Cool','Code':001},{'FeatureId':3,'FeatureName':'Nice','Code':001},
[{'FeatureId':4,'FeatureName':'Pretty','Code',002},{'FeatureId':5,'FeatureName':'Beautiful','Code':002}

];

for now am just considering 3 arrays however I will have 9 arrays in total.
My resulting array should combine the elements with key as Code.
Here if you see ItemFeatures has 2 elements with similar code 001 and 002 and so it will be converted to a subarray.
And so the result should be something as below.
[{'Item_Id':1,'Item_Name':'Soap','ItemPrice_Id':1,'ItemPrice_ItemId':1,'Price':'10$','ItemFeatures': [{'FeatureId':2,'FeatureName':'Cool'},{'FeatureId':3,'FeatureName':'Nice'}]
},
{'Item_Id':2,'Item_Name':'Powder','ItemPrice_Id':2,'ItemPrice_ItemId':2,'Price':'20$','ItemFeatures': [{'FeatureId':4,'FeatureName':'Pretty'},{'FeatureId':5,'FeatureName':'Beautiful'}]
}];

];
Here in the example ItemFeatures is converted to a subarray as it has multiple items with same Code.
I will have two more arrays which will have multiple items with same Code.
And the way the ItemFeatures sub-array is there in the resulting array, I will need the other subarrays too.
How should I do this? Can you please help me out here in resolving this.
Am a newbie to JS and bit stuck.

A: You can use a combination of Array.map, Array.find, Array.filter and Object.assign to find matching objects and merge them into one:


var Items = [{'Item_Id':1,'Item_Name':'Soap','Code':001}, {'Item_Id':2,'Item_Name':'Powder','Code':002}]
var ItemPrice = [{'ItemPrice_Id':1,'ItemPrice_ItemId':1,'Price':'10$','Code':001}, {'ItemPrice_Id':2,'ItemPrice_ItemId':2,'Price':'20$','Code':002}];
var ItemFeatures = [{'FeatureId':2,'FeatureName':'Cool','Code':001},{'FeatureId':3,'FeatureName':'Nice','Code':001}, {'FeatureId':4,'FeatureName':'Pretty','Code': 002}, {'FeatureId':5,'FeatureName':'Beautiful','Code':002}];

// convert Items into another array of objects
const merged = Items.map((item) => {
  // add all of the matching ItemPrice properties to Item
  return Object.assign(item, ItemPrice.find(iprice => iprice.Code === item.Code), {
    // add a key "ItemFeatures" with matching ItemFeatures
    ItemFeatures: ItemFeatures.filter(feature => feature.Code === item.Code)
  });
});

console.log(merged);


