Mayank Jain Mayank Jain - 17 days ago 5
Javascript Question

Merge one JSON and JSON array on the basis of JSON's value and JSON Array's key

I wanna try to create one JSON array in node by combine these two JSON and JSON arrays

`var template = {
"key1": "value1",
"key3": "value3",
"key4": "value3",
"key6": "Dummy Value1"
};
var data = [
{
"value1": "1",
"value2": "2",
"value3": "3"
},
{
"value1": "11",
"value2": "12",
"value3": "13"
},
{
"value1": "21",
"value2": "22",
"value3": "23"
}
];`


I need Resulted JSON be like

var result = [
{
"key1": "1",
"key3": "3",
"key4": "3",
"key6": "Dummy Value1"
},
{
"key1": "11",
"key3": "13",
"key4": "13",
"key6": "Dummy Value1"
},
{
"key1": "21",
"key3": "23",
"key4": "23",
"key6": "Dummy Value1"
}
]


In my case there will be around 40 keys in JSON array and around 25 keys in template JSON, So I'm also looking for Optimized solution for this. Anybody can help me in this?

Answer

Use Array#map and Array#reduce methods.

// iterate over the array
var res = data.map(function(o) {
  // get the property names array and iterate to generate 
  // result object
  return Object.keys(template).reduce(function(obj, k) {
    // define property based on the array element object has 
    // the prefered property or not
    obj[k] = o.hasOwnProperty(template[k]) ? o[template[k]] : template[k];
    // return the object reference
    return obj;
    // set initial value as an empty object which is used as
    // the new array element 
  }, {});
});

var template = {
  "key1": "value1",
  "key3": "value3",
  "key4": "value3",
  "key6": "Dummy Value1"
};
var data = [{
  "value1": "1",
  "value2": "2",
  "value3": "3"
}, {
  "value1": "11",
  "value2": "12",
  "value3": "13"
}, {
  "value1": "21",
  "value2": "22",
  "value3": "23"
}];

var res = data.map(function(o) {
  return Object.keys(template).reduce(function(obj, k) {
    obj[k] = o.hasOwnProperty(template[k]) ? o[template[k]] : template[k];
    return obj;
  }, {});
});

console.log(res);