如何在JavaScript中按键使用mapKeys和group值?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (105)

我有这个对象:

let root = {};
root["myRootNode"] = { 
   id1: {
     age: "17",
     name: "name1",
     surname: "surname1"                    
  },
   id2: {
     age: "11",
     name: "name2",
     surname: "surname2"                    
  },
   id3: {
     age: "25",
     name: "name1",
     surname: "surname3"                    
  }
};

而我想用它来做的就是让它进入状态:

"name1": [
  {
     age: "17",
     surname: "surname1"         
  },
  {
     age: "25",
     surname: "surname3"         
  }
],
"name2": [
    age: "11",
    surname: "surname2"        
]

对我来说,拥有所有对象的列表/数组非常重要,这些对象包含同一属性,并按该属性的值进行分组。

我尝试过:

let test = _.mapKeys(root["myRootNode"], function(value, key) {
  return value["name"];
});

但这给了我结果:

"name1": {
   age: "25"
   name: "name1"
   surname: "surname3"
},
"name2": {
   age: "11"
   name: "name2"
   surname: "surname2"
}

因此它们没有分组,只有最后一个值映射到重复的键下。同样在我得到的结果中,它们不会放在数组下面。

提问于
用户回答回答于

我们的想法是为每个新名称创建一个数组,并将所有条目推送到相应的名称数组。

const root = {
  myRootNode: {
    id1: {
      age: "17",
      name: "name1",
      surname: "surname1"
    },
    id2: {
      age: "11",
      name: "name2",
      surname: "surname2"
    },
    id3: {
      age: "25",
      name: "name1",
      surname: "surname3"
    }
  }
};

const result = Object.values(root.myRootNode).reduce((a, e) => {
  if (!(e.name in a)) {
    a[e.name] = [];
  }

  a[e.name].push({
    age: e.age,
    surname: e.surname
  });

  return a;
}, {});

console.log(JSON.stringify(result, null, 4));
用户回答回答于

可以使用groupBy并映射它的值来摆脱属性。

就个人而言,你应该使用数组而不是对象:

const res =
_(root.myRootNode)
  .groupBy('name')
  .mapValues((arr)=>_.map(arr, (o) =>_.omit(o,['name'])))
  .value()



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

<script>
let root = {};
root["myRootNode"] = { 
   id1: {
     age: "17",
     name: "name1",
     surname: "surname1"                    
  },
   id2: {
     age: "11",
     name: "name2",
     surname: "surname2"                    
  },
   id3: {
     age: "25",
     name: "name1",
     surname: "surname3"                    
  }
};
</script>

扫码关注云+社区

领取腾讯云代金券