0

In example, I have these 2 JSON Objects

jsonObject1 = [
             {"id": "1", "name": "name1", "children": [{"id": "2", "name": "name2"}] },
             {"id": "3", "name": "name3", "children": [{"id": "4", "name": "name4"}] }
             ];

jsonObject2 =[
             {"id": "4", "name": "name1", "children": [{"id": "6", "name": "name5"}] },
             {"id": "5", "name": "name3", "children": [{"id": "7", "name": "name6"}] }
             ]

How do I merge the 2 JSONObject into 1 matching on the outer object name and get this result?

mergedJsonObject = jsonObject1.merge(jsonObject2);

mergedJsonObject = [
                    {"id": "1", "name": "name1", "children": [
                                                             {"id": "2", "name": "name2"}, 
                                                             {"id": "6", "name": "name5"}
                                                             ] 
                    },
                    {"id": "3", "name": "name3", "children": [
                                                             {"id": "4", "name": "name4"},
                                                             {"id": "7", "name": "name6"}
                                                             ] 
                    }
                    ];
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ronaldo
  • 263
  • 5
  • 18

2 Answers2

1

Since the objects in question happen to be JSONArrays, why not (pseudocode):

  merge (arr1, arr2) {
     for (int i=0; i < arr2.length, i++) {
        JSONObject row = arr2.get(i)
        arr1.add(row)
     }
     return arr1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

Try something like the following.

for o1 in jsonObject1
    for o2 in jsonObject2
        if o1['name'] == o2['name']
           o1['children'].push(o2['children'])
// inspect jsonObject1

There's probably a better way to do this than a nested loop, but whatever

And make sure that you aren't inserting an array into the other array, but rather adding all the elements

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I didn't downvote (in fact, I upvoted). But the OP didn't explicitly say he WANTED to eliminate duplicates...Nevertheless - interesting solution :) – paulsm4 Oct 16 '17 at 20:43
  • @paulsm4 Pretty sure "How do I merge the 2 JSONObject into 1" implies that. Am I wrong? – OneCricketeer Oct 16 '17 at 21:12