10

I need to merge JSON objects with same key into one so that it gets an object or array(doesn't matter if result is an object or array) which holds the key and an array for the values

example JSON object:

[{
    "meine_frage": "hier kommt die antwort",
    "ne_andere_frage": "ne andere antwort",
    "was_willst_du": "alles",
    "mehr_zur_auswahl": ["einiges", "vieles und", "g\u00e4r nix"]

}, {
    "meine_frage": "tom & jerry",
    "ne_andere_frage": "mickey maus",
    "was_willst_du": "oder",
    "mehr_zur_auswahl": ["manches", "einiges", "vieles und", "g\u00e4r nix"]

}, {
    "meine_frage": "dick und doof",
    "ne_andere_frage": "minnie muas",
    "was_willst_du": "nichts",
    "mehr_zur_auswahl": ["g\u00e4r nix"]

}]

result should look like:

[{
    "meine_frage": ["hier kommt die antwort", "tom & jerry", "dick und doof"],
    "ne_andere_frage": ["ne andere antwort", "mickey maus", "minnie muas"],
    "was_willst_du": ["alles", "oder"],
    "mehr_zur_auswahl": ["einiges", "vieles und", "g\u00e4r nix", "manches", "einiges", "vieles und", "g\u00e4r nix"]
}]

some values are already arrays whereas others not, the keys are genterated dynamically so assume the the key name is unkown

i tried iterating over the key/values with $.each and for loops but without success, also searched the web but couldnt find similar, appreciate any help

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
prince
  • 123
  • 1
  • 1
  • 8

6 Answers6

11

You can use reduce() and concat() methods for this.

const data = [{"meine_frage":"hier kommt die antwort","ne_andere_frage":"ne andere antwort","was_willst_du":"alles","mehr_zur_auswahl":["einiges","vieles und","gär nix"]},{"meine_frage":"tom & jerry","ne_andere_frage":"mickey maus","was_willst_du":"oder","mehr_zur_auswahl":["manches","einiges","vieles und","gär nix"]},{"meine_frage":"dick und doof","ne_andere_frage":"minnie muas","was_willst_du":"nichts","mehr_zur_auswahl":["gär nix"]}]

const result = data.reduce(function(r, e) {
  return Object.keys(e).forEach(function(k) {
    if(!r[k]) r[k] = [].concat(e[k])
    else r[k] = r[k].concat(e[k])
  }), r
}, {})

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • This is good and quite close to being functional. With a few tweaks you could make it so: replace the if/else and assignments with a ternary return statement, and use that function in [array_map_associative](https://stackoverflow.com/a/43004994/760706). – Nicholas Shanks Dec 21 '17 at 17:37
5

You could use reduce method by passing a callback function as parameter.

The algorithm is follow: if final object already contains one key then you should initialize the key's value with an empty array. Otherwise, you should append to array value from all items from the array.

let data = [{"meine_frage":"hier kommt die antwort","ne_andere_frage":"ne andere antwort","was_willst_du":"alles","mehr_zur_auswahl":["einiges","vieles und","gär nix"]},{"meine_frage":"tom & jerry","ne_andere_frage":"mickey maus","was_willst_du":"oder","mehr_zur_auswahl":["manches","einiges","vieles und","gär nix"]},{"meine_frage":"dick und doof","ne_andere_frage":"minnie muas","was_willst_du":"nichts","mehr_zur_auswahl":["gär nix"]}]

let result = data.reduce(function(obj, item){
  Object.keys(item).forEach(function(key){
    if(!obj[key]) obj[key] = [].concat(item[key])
    else {
       if(Array.isArray(item[key]))
         obj[key].push(...item[key])
       else
         obj[key].push(item[key]);
    }
  });
  return obj;
},{});
console.log([result]);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
3

This function will do the work:

const example = array => {
    let newObject = {}
    array.forEach((element) => {
        for(let key in element) {
            if(typeof element[key] === 'object') {
                element[key].forEach((el) => {
                    if(newObject[key] && newObject[key].length) {
                         newObject[key].push(el)
                    }
                    else {
                        newObject[key] = [el]
                    }
                })
            }
            else {
                if(newObject[key] && newObject[key].length){
                    newObject[key].push(element[key])
                }
                else{
                    newObject[key] = [element[key]]
                }
            }
        }
    })
    return newObject
}
Sergio
  • 1,370
  • 11
  • 12
2

Use map and check by Array.isArray, try below code

var myArray = [{"meine_frage": "hier kommt die antwort","ne_andere_frage": "ne andere antwort","was_willst_du": "alles","mehr_zur_auswahl": ["einiges", "vieles und", "g\u00e4r nix"]}, {"meine_frage": "tom & jerry","ne_andere_frage": "mickey maus","was_willst_du": "oder","mehr_zur_auswahl": ["manches", "einiges", "vieles und", "g\u00e4r nix"]}, {"meine_frage": "dick und doof","ne_andere_frage": "minnie muas","was_willst_du": "nichts","mehr_zur_auswahl": ["g\u00e4r nix"]}];

var findKeyOf = function(key){ 
  var temp = myArray.map(function(e){
    return e[key]; 
  });
  var test = [];
  for(let i in temp){
    if(Array.isArray(temp[i]) ){
      test = test.concat(temp[i]);
    }else{
      test.push(temp[i])
    }
  }
  return test;
};

var newArr = [
    {meine_frage:findKeyOf('meine_frage')},
    {ne_andere_frage:findKeyOf('ne_andere_frage')},
    {was_willst_du:findKeyOf('was_willst_du')},
    {mehr_zur_auswahl:findKeyOf('mehr_zur_auswahl')},
]
console.log(newArr);
freelancer
  • 1,174
  • 5
  • 12
2

You can use array#reduce as a accumulator and iterate through each key of object and array#concat the values.

var data = [{ "meine_frage": "hier kommt die antwort", "ne_andere_frage": "ne andere antwort", "was_willst_du": "alles", "mehr_zur_auswahl": ["einiges", "vieles und", "g\u00e4r nix"] }, { "meine_frage": "tom & jerry", "ne_andere_frage": "mickey maus", "was_willst_du":"oder", "mehr_zur_auswahl": ["manches", "einiges", "vieles und", "g\u00e4r nix"] }, { "meine_frage": "dick und doof", "ne_andere_frage": "minnie muas", "was_willst_du": "nichts", "mehr_zur_auswahl": ["g\u00e4r nix"] }];

var merged = data.reduce((r,o) => {
  Object.keys(o).forEach(k => {
    r[k] = (r[k] || []).concat(o[k]);
  })
  return r;
},{});

console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
2

Using reduce and spread operator

var data = [{
    "meine_frage": "hier kommt die antwort",
    "ne_andere_frage": "ne andere antwort",
    "was_willst_du": "alles",
    "mehr_zur_auswahl": ["einiges", "vieles und", "g\u00e4r nix"]

}, {
    "meine_frage": "tom & jerry",
    "ne_andere_frage": "mickey maus",
    "was_willst_du": "oder",
    "mehr_zur_auswahl": ["manches", "einiges", "vieles und", "g\u00e4r nix"]

}, {
    "meine_frage": "dick und doof",
    "ne_andere_frage": "minnie muas",
    "was_willst_du": "nichts",
    "mehr_zur_auswahl": ["g\u00e4r nix"]

}]

let myData = data.reduce((b , a)=> {
    Object.keys(a).forEach(key => {
        if (Object.keys(b).indexOf(key) > -1) {
            if (typeof a[key] === "object") {
                b[key] = [...b[key], ...a[key]]       
            } else {
                b[key].push(a[key])
            }
             
        } else {
            if (typeof a[key] === "object") {
                b[key] = [...a[key]]
            } else {
                b[key] = [a[key]]
            }                  
        }    
    })
    return b
}, {})

console.log(myData)
.as-console-wrapper { max-height: 100% !important; top: 0; }
edkeveked
  • 17,989
  • 10
  • 55
  • 93