简体   繁体   中英

Node.js object array data joins

Are there any libraries or efficient techniques to perform array joins in node JS such that,

A = [ { a: 1, b: 'a' }, { a: 2, b:'b' }, { a: 3, b: 'a' }, { a: 4, b: 'b' } ]
B = [ { a: 1, c: true }, { a: 2, c: true }, { a: 3, c: false } ]

could be joined such that the following results could be produced:

# Intersection on a
C = [ { a: 1, b: 'a', c: true }, { a: 2, b: 'b', c: true }, { a: 3, b: 'a', c: false } ]

# Union on a
D = [ { a: 1, b: 'a', c: true }, { a: 2, b: 'b', c: true }, { a: 3, b: 'a', c: false }, { a: 4, b: 'b' } ]

Is array.map the best solution to this problem?

efficiency is paramount here, since it could be handling huge arrays in production

You're not very specific about how you identify and merge your object.

Using Underscore, the result can be obtained as follow:

_u=require("underscore")
A = [ { a: 1, b: 'a' }, { a: 2, b:'b' }, { a: 3, b: 'a' }, { a: 4, b: 'b' } ]
B = [ { a: 1, c: true }, { a: 2, c: true }, { a: 3, c: false } ]

D = _u.zip(A,B).map( 
      function(x){ 
        return _u.extend(x[0],x[1]);
      } 
    );

C = _u.zip(A,B).filter(
      function(x){ 
        return !!x[1];
      }
    ).map(
      function(x){ 
        return _u.extend(x[0],x[1]);
      }
    );

Is that what you're looking for ?

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