找到键并创建新对象

时间:2015-04-02 06:27:25

标签: javascript lodash

我有这个对象数组:

[{
    "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中做到这一点?

2 个答案:

答案 0 :(得分:1)

这是我的方法:

_(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()对原始集合中的所有字段值进行采样。

答案 1 :(得分:0)

我认为最终你想拥有一个对象数组而不是一个对象。如果我理解正确 - 使用lodash函数的组合(链接到jsbin):

_.reduce(arr, function(result, item, index) {
  _.forEach(item, function(value, key) {
    var resulted = _.find(result, { field_name: key });
    if (!resulted) {
      resulted = { field_name: key, sample: [] };
      result.push(resulted);
    }
    resulted.sample.push(value);
  });
  return result;
}, []);