代码之家  ›  专栏  ›  技术社区  ›  R111

如何在嵌套属性上使用javascript lodash uniqBy

  •  1
  • R111  · 技术社区  · 8 年前

    我有一个结构类似于以下的对象(简化版本):

    {
       "time": 100,
       "complete" : true,
       "results" : {
           "total": 10,
           "score": 3,
           "results": [ 
               {
               "id" : 123,
               "name": "test123"
                },
                {
               "id" : 123,
               "name": "test4554"
                }
              ]
           }     
     }
    

    如何使用lodash ._uniqBy 要消除重复数据,请基于 results.results.id 成为唯一的钥匙?

    为了澄清,我希望在原始对象结构中返回已消除重复的结果集,例如:。

     {
       "time": 100,
       "complete" : true,
       "results" : {
           "total": 10,
           "score": 3,
           "results": [ 
               {
               "id" : 123,
               "name": "test123"
                }
              ]
           }     
     }
    

    谢谢

    2 回复  |  直到 8 年前
        1
  •  1
  •   lankovova    8 年前

    只需将对象的正确部分传递到 _.uniqBy(array, [iteratee=_.identity]) 作用

    下一步你要做的是“浓缩”lodash uniqBy 结果和对象。这有点棘手。我建议您使用 ES6 Object.assign() 方法和 传播 操作人员

    查看我的解决方案。希望这有帮助。

    const myObj = {
      "time": 100,
      "complete" : true,
      "results" : {
        "total": 10,
        "score": 3,
        "results": [
          {"id" : 123, "name": "test123"},
          {"id" : 123, "name": "test4554"}
        ]
      }     
    };
    
    const uniq = _.uniqBy(myObj.results.results, 'id');
    const resultWrapper = Object.assign({}, myObj.results, { results: [...uniq] });
    const resultObj = Object.assign({}, myObj, { results: resultWrapper });
    
    console.log( resultObj );
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
        2
  •  0
  •   Денис Кублицкий    8 年前

    你可以用这样的东西

    const myObj = {
      time: 100,
      complete : true,
      results : {
        total: 10,
        score: 3,
        results: [
          {id : 123, name: "test123"},
          {id : 123, name: "test4554"}
        ]
      }     
    };
    
    _.set(myObj, 'results.results', _.uniqBy(_.get(myObj, 'results.results'), 'id'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>