lodash groupBy条件对params

时间:2018-04-06 13:28:28

标签: lodash

我正在尝试用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

1 个答案:

答案 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);