2015-04-02 40 views
0

我有這樣的對象數組:找到鑰匙,並創建新的對象

[{ 
    "f_name":"nand", 
    "lastName":"bhatt", 
    "gender":"", 
    "email":"[email protected]", 
    "mobileNo":"0043 664 321 54 76", 
    "company":"IBM Bhimtal" 
}, { 
    "f_name":"Pooran", 
    "lastName":"Pradhan", 
    "gender":"male", 
    "email":"[email protected]", 
    "mobileNo":"13123123123", 
    "company":"Google" 
}, { 
    "f_name":"Krishna", 
    "lastName":"Bhatt", 
    "gender":"Male", 
    "email":"[email protected]", "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: ['[email protected]','[email protected]','[email protected]'], 
    field_name:mobileNo, sample: ['0043 664 321 54 76','13123123123','983232324'], 
}] 

任何想法,我們應該怎麼在lodash做到這一點?

回答

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()來對原始集合中的所有字段值進行採樣。

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; 
}, []); 
+0

簡單的_.map解決了我的問題。 – 2015-04-03 00:22:10