【问题标题】:Merge two JSON array on condition in Lodash在 Lodash 中按条件合并两个 JSON 数组
【发布时间】:2018-06-05 05:02:29
【问题描述】:

我有两个 JSON 数组,例如:

var a = [{_id:1, name: "Bhavin"},{_id:2, name: "Raj"},{_id:3, name: "Rahul"}];    
var b = [{_id:1, post: "Developer"},{_id:2, post: "Quality Analyst"}];

现在,我想合并 Like:

var c = [{_id:1, name: "Bhavin", post: "Developer"},{_id:2, name: "Raj", post: "Quality Analyst"},{_id:3, name: "Rahul"}];

我知道我可以通过使用两个 for 循环在纯 JavaScript 中轻松完成...但这需要 n*n 时间。

我只想在n 时间内解决这个问题。

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript ecmascript-6 lodash


    【解决方案1】:

    你应该使用lodashmergeWith函数。

    var a = [{_id:1, name: "Bhavin"},{_id:2, name: "Raj"},{_id:3, name: "Rahul"}];
    
    var b = [{_id:1, post: "Developer"},{_id:2, post: "Quality Analyst"}];
    
    
    // ouput [{_id:1, name: "Bhavin", post: "Developer"},{_id:2, name: "Raj", post: "Quality Analyst"},{_id:3, name: "Rahul"}];
    
    function customizer(firstValue, secondValue) {
      return Object.assign({}, firstValue, secondValue);
    }
    
    console.log(_.mergeWith(a, b, customizer));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

    【讨论】:

      【解决方案2】:

      您可以通过将较小的数组映射到键值组合对象来轻松解决此问题,其中对象的键是 id,它们的值是关联的值本身。完成关联后,我们可以通过分配映射对象中的缺失值来迭代和转换更大的数组。

      // ensure that b has more items than a
      // to prevent data loss
      if(a.length > b.length) {
        var t = b;
        b = a;
        a = t;
      }
      
      // create an object composed of of ids as key associated with each object.
      // a loash alternative is: 
      // var map = _.keys(a, '_id');
      var map = a.reduce((r, v) => (r[v._id] = v, r), {});
      
      // assign missing properties from each object from the associated mapped object.
      var result = b.map(v => ({...map[v._id], ...v}));
      

      var a = [{_id:1, name: "Bhavin"},{_id:2, name: "Raj"},{_id:3, name: "Rahul"}];
      var b = [{_id:1, post: "Developer"},{_id:2, post: "Quality Analyst"}];
      
      // ensure that b has more items than a
      // to prevent data loss
      if(a.length > b.length) {
        var t = b;
        b = a;
        a = t;
      }
      
      // create an object composed of of ids as key associated with each object.
      // a loash alternative is: 
      // var map = _.keys(a, '_id');
      var map = a.reduce((r, v) => (r[v._id] = v, r), {});
      
      // assign missing properties from each object from the associated mapped object.
      var result = b.map(v => ({...map[v._id], ...v}));
      
      console.log(result);
      .as-console-wrapper{min-height:100%;top:0}

      【讨论】:

        【解决方案3】:

        O(n) 时间用纯 Javascript 实现这一点是完全可能的:

        var a = [{_id:1, name: "Bhavin"},{_id:2, name: "Raj"},{_id:3, name: "Rahul"}];
        var b = [{_id:1, post: "Developer"},{_id:2, post: "Quality Analyst"}];
        
        const aById = a.reduce((map, { _id, name }) => map.set(_id, name), new Map());
        const bById = b.reduce((map, { _id, post }) => map.set(_id, post), new Map());
        const combined = [...aById.entries()].map(([_id, name]) => {
          const person = { _id, name };
          const post = bById.get(_id);
          if (post) person.post = post;
          return person;
        });
        
        console.log(combined);
        var c = [{_id:1, name: "Bhavin", post: "Developer"},{_id:2, name: "Raj", post: "Quality Analyst"},{_id:3, name: "Rahul"}];

        Maps 保证有O(1) 查找时间。对象哈希图(如{'1': 'Developer', '2': 'Quality Analyst'})不是。

        您的原始代码中有几个拼写错误,我假设这些是无意的 - 我在上面的 sn-p 中修复了它们。

        【讨论】:

          【解决方案4】:

          您好,您可以使用以下代码实现它

          _.map(a, function (el){
             return _.merge(el , _.find(b, {_id: el._id }))
          })
          
          // using chain, i would prefer first it looks clean :-p
          _.chain(a).map(function (o){
             return _.merge(o, _.find(b, {_id: o._id }))
          })
          .value()
          

          我会用链尝试它并更新答案

          【讨论】:

          • 这还不是 O(n*n) 吗?
          猜你喜欢
          • 2021-12-10
          • 1970-01-01
          • 2016-03-22
          • 1970-01-01
          • 1970-01-01
          • 2017-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多