gpt4 book ai didi

javascript - 找到键并创建新对象

转载 作者:行者123 更新时间:2023-12-03 10:25:47 28 4
gpt4 key购买 nike

我有这个对象数组:

[{
"f_name":"nand",
"lastName":"bhatt",
"gender":"",
"email":"chuchubhatt@webuters.com",
"mobileNo":"0043 664 321 54 76",
"company":"IBM Bhimtal"
}, {
"f_name":"Pooran",
"lastName":"Pradhan",
"gender":"male",
"email":"pp@wt.com",
"mobileNo":"13123123123",
"company":"Google"
}, {
"f_name":"Krishna",
"lastName":"Bhatt",
"gender":"Male",
"email":"krishna@wt.com", "mobileNo":"983232324",
"company":"IBM"
}];

我想要一个与此类似的新对象:

[
{
field_name:f_name, sample: ['nand','Pooran','Krishna'],
field_name:lastName, sample: ['bhatt','Pradhan','Bhatt'],
field_name:gender, sample: ['','male','Male'],
field_name:email, sample: ['chuchubhatt@webuters.com','pp@wt.com','krishna@wt.com'],
field_name:mobileNo, sample: ['0043 664 321 54 76','13123123123','983232324'],
}]

知道我们应该如何在 lodash 中做到这一点吗?

最佳答案

这是我的方法:

_(collection)
.map(_.keys)
.flatten()
.uniq()
.map(function(item) {
return {
field_name: item,
sample: _.pluck(collection, item)
};
}).value();

前三个电话 map() , flatten() ,和uniq() ,为您提供一组可供使用的键。下一次调用 map() 会生成输出集合。由于您要映射键,因此 field_name 属性只是 item 参数。 sample 属性使用 pluck()从原始集合中采样所有字段值。

关于javascript - 找到键并创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29406361/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com