-5
    var a=[{"id":1,"total":1000},{"id":2,"total":2000}]
    var b=[{"id":1,"credit":500},{"id":2,"credit":1000}]
    var c=[{"id":1,"reversed":500},{"id":2,"amount":1000}]

I want something like this,

var newArray=[{"id":1,
                       "amount":
                         {"total":1000,"credit":500,"reversed":500}}
                       {"id":2,
                       "amount":
                         {"total":2000,"credit":1000,"reversed":1000}}
               ]

Is it possible to achieve this via a JavaScript function?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Yes, it's possible. Take a stab at it. If you get stuck, post what you've tried, and we can help you with it. – T.J. Crowder Nov 16 '16 at 12:11
  • Separately: That's not JSON. JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. Those are just JavaScript objects. Specifically, they're arrays with objects inside. – T.J. Crowder Nov 16 '16 at 12:11
  • come on, what have you tried ? Of course it's possible. Try looping and let us know how you get on – thatOneGuy Nov 16 '16 at 12:18

2 Answers2

0

Try this way with extend and each

    var a=[{"id":1,"total":1000},{"id":2,"total":2000}];
    var b=[{"id":1,"credit":500},{"id":2,"credit":1000}];
    var c=[{"id":1,"reversed":500},{"id":2,"amount":1000}];
    
    
    var result = $.extend(true, {}, a, b,c);
    
    var newArray = [];
    $.each(result,function(index,value){
      var ind = value.id;
      delete value['id']; //unset id here
      var amount = value;
      newArray.push({id: ind,amount:amount});
    });

    console.log(newArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

You could use a hash table as reference to the objects with the same id. Iterate all arrays and with sub arrays take the keys and assign the value to the referenced object.

Method used:

var array1 = [{ "id": 1, "total": 1000 }, { "id": 2, "total": 2000 }],
    array2 = [{ "id": 1, "credit": 500 }, { "id": 2, "credit": 1000 }],
    array3 = [{ "id": 1, "reversed": 500 }, { "id": 2, "amount": 1000 }],
    hash = Object.create(null),
    result = [];

[array1, array2, array3].forEach(function (a) {
    a.forEach(function (o) {
        if (!hash[o.id]) {
            hash[o.id] = {};
            result.push(hash[o.id]);
        }
        Object.keys(o).forEach(function (k) {
            hash[o.id][k] = o[k];
        });
    });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392