我正在尝试用lodash .....或者ES7转换它
[
{
"name":"Rue Pierre",
"details":{
"name":"Rue Pierre"
}
},
{
"name":"Rue de Wavrin",
"details":{
"ref":"D 241",
"name":"Rue de Wavrin"
}
},
{
"name":"Rue de paris",
"details":{
"ref":"D 241",
"name":"Rue de paris"
}
}
]
在
{
"Rue Pierre": [
{ "name": "Rue Pierre", "details": { "name": "Rue Pierre Gilles de Gennes" }}
],
"D 241': [
{"name": "Rue de paris", "details": {"ref": "D 241", "name": "Rue de paris"}},
{"name": "Rue de Wavrin", "details": { "ref": "D 241", "name": "Rue de Wavrin" }}
]
}
如果属性'ref'存在i groupBy“ref”否则groupBy“name”。 这可能一步到位吗?
THX
答案 0 :(得分:1)
_.groupBy()
接受谓词。在谓词中,您可以使用_.get()
从对象获取路径的值(' details.ref'),如果值未定义,则使用默认值(UITabBarController
)而不是。
o.name

const data = [{"name":"Rue Pierre","details":{"name":"Rue Pierre"}},{"name":"Rue de Wavrin","details":{"ref":"D 241","name":"Rue de Wavrin"}},{"name":"Rue de paris","details":{"ref":"D 241","name":"Rue de paris"}}];
const result = _.groupBy(data, (o) => _.get(o, 'details.ref', o.name));
console.log(result);