【问题标题】:Change key of and group javascript objects with lodash使用 lodash 更改和分组 javascript 对象的键
【发布时间】:2017-12-10 18:23:27
【问题描述】:

我有一个结构如下的对象:

{  
   guid x: { id: guid x, fooid: guid a, c: "baz"}, 
   guid y: { id: guid y, fooid: guid a, c: "baz"}, 
   guid z: { id: guid z, fooid: guid b, c: "baz"} 
}

我想使用 fooid 作为键。但是有些对象有相同的 fooid 并且应该被分组(这里作为一个数组但也可以是对象):

{  
   guid a : [{ id: guid x, fooid: guid a, c: "bar"},{ id: guid y, 
                fooid: guid a, c: "bar"}],
   guid b : { id: guid z, fooid: 3, c: "bar"} 
}

我尝试使用 lodash 执行此操作,但没有成功,感谢任何帮助!试图寻找解决方案,但我不确定术语是什么,这使它非常困难。

【问题讨论】:

  • 什么是id (1)
  • 你确定你不是从数组开始的吗?显示的语法对对象键无效,但对 "groupBy" 结果对象 有意义
  • 我想表明key与内部对象中的id相同。不知道怎么表达才清楚? { guid x : { id: guid x, fooid: guid y, c: "bar"}, guid z : { id: guid z, fooid: guid y, c: "bar"}, guid k : { id: guid k, fooid: guid j, c: "bar"} } 这是一个对象,我试图简化的尝试可能搞砸了语法。
  • 仍然不清楚你实际上是从什么开始的。你确定它是一个对象还是一个数组?
  • 这是一个嵌套对象的对象,我敢肯定。那是故意的,并使用规范化器 (github.com/paularmstrong/normalizr) 创建。我更新了这个问题,我认为至少原始语法是正确的?

标签: javascript object lodash


【解决方案1】:

使用 lodash 的_.groupBy():

var data = {  
   "guid x": { id: "guid x", fooid: "guid a", c: "baz"}, 
   "guid y": { id: "guid y", fooid: "guid a", c: "baz"}, 
   "guid z": { id: "guid z", fooid: "guid b", c: "baz"} 
};

var result = _.groupBy(data, 'fooid');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

【讨论】:

    【解决方案2】:

    使用 lodash 我认为这就是您要寻找的东西

    var data ={  
       1 : { id: 1, fooid: 200, c: "baz"} ,
       2 : { id: 2, fooid: 200, c: "baz"} ,
       3 : { id: 3, fooid: 300, c: "baz"} ,
    }
    
    var res = _(data)
                .values()
                .groupBy('fooid')
                .value()
    
    console.log(res)
    .as-console-wrapper {	max-height: 100%!important;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

    【讨论】:

      【解决方案3】:

      试试这个,注意我用过 ES6 语法

      var obj = {  
         id1: { id: 1, fooid: 2, c: "baz"},
         id2: { id: 2, fooid: 2, c: "baz"},
         id3: { id: 3, fooid: 3, c: "baz"} 
      };
      
      const newObj = Object.keys(obj).reduce((oldVal, newKey) => {
        
        const key = 'fooid' + obj[newKey]['fooid'];
        
        if(!oldVal.hasOwnProperty(key)){
          oldVal[key] = [];
        }
       
       
        oldVal[key].push(obj[newKey])
        
        return oldVal;
        
      },{});
      
      console.log(newObj);

      【讨论】:

      • 你可以使用lodash的reduce方法。
      猜你喜欢
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2020-12-18
      • 2021-05-04
      • 1970-01-01
      相关资源
      最近更新 更多