简体   繁体   中英

Using JS Underscore to merge and sort similar arrays by key

I have two arrays:

"array_one":
[
    {
    "id": 1,
    "name": One
     },
     {
     "id": 2,
     "name": Two
     }
]

"array_two":
[
    {
    "id": 1,
    "name": Uno
     },
     {
     "id": 3,
     "name": Three
     }
]

I need to use Underscore to:

  1. Overwrite all objects in array_one with objects that have a matching id from array_two.

  2. Append all objects from array_two into array_one if no other object with their id exists there already.

  3. Overwritten objects should retain their index in the array

  4. Appended objects must be added at the end of the array

So the final result looks like:

"array_final":
[
    {
    "id": 1,
    "name": Uno
     },
    {
    "id": 2,
    "name": Two
     },
     {
     "id": 3,
     "name": Three
     }
]

You can use two objects as hash tables one to keep track of added objects and another for second array. Then you use reduce to replace objects from first array if found in second array and finally you use one more for loop to add rest of objects from second array.

 var data = { "array_one": [{ "id": 1, "name": 'One' }, { "id": 2, "name": 'Two' }], "array_two": [{ "id": 1, "name": 'Uno' }, { "id": 3, "name": 'Three' }] } var obj = {}, added = {} data.array_two.forEach(e => obj[e.id] = e) var result = {finalArray: data.array_one.reduce(function(r, e) { r.push(obj[e.id] ? (added[e.id] = 1, obj[e.id]) : e); return r; }, [])} for(var i in obj) if(!added[obj[i].id]) result.finalArray.push(obj[i]) console.log(result) 

 var array1 = [ { "id": 1, "name": 'One' }, { "id": 2, "name": 'Two' } ]; var array2 = [ { "id": 1, "name": 'Uno' }, { "id": 3, "name": 'Three' } ]; function mapArrays(arr1, arr2) { var tmp = _.map(arr1, function(val) { var o = _.first(_.filter(arr2, function(a2) { return a2.id === val.id; })); return !!o ? o : val; }); return _.union(tmp, _.filter(arr2, function(val) { return !_.some(tmp, function(a2) { a2.id == val.idl }); })); } var final = mapArrays(array1, array2); console.log(final); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM