使用lodash将JSON对象数组转换为哈希映射

时间:2017-11-30 19:46:40

标签: javascript json lodash

我需要转换

var data = [
{ rel: 'links-A', href: 'url1', id: 0},
{ rel: 'links-A', href: 'url2', id: 1},
{ rel: 'links-B', href: 'url3', id: 2},
{ rel: 'links-B', href: 'url4', id: 3},
];

到这样的哈希映射:

var converted = {
linksA: [
        {href: 'url1', id: 0},
        {href: 'url2', id: 1}
                 ],
linksB: [
        {href: 'url3', id: 2},
        {href: 'url4', id: 3}
        ],
}

不确定它是否适用于lodash

2 个答案:

答案 0 :(得分:2)

首先groupBy rel然后使用mapKeys在键上映射以删除连字符:

var converted = _(data)
    .groupBy('rel')
    .mapKeys( (v, k) => k.replace('-', ''))
    .value();

答案 1 :(得分:1)

如果你不想,你甚至不必使用lodash。 .reduce数组方法应该足够了:



var data = [
{ rel: 'links-A', href: 'url1', id: 0},
{ rel: 'links-A', href: 'url2', id: 1},
{ rel: 'links-B', href: 'url3', id: 2},
{ rel: 'links-B', href: 'url4', id: 3},
]

var converted = data.reduce((final, current) => {
  var newKey = current.rel.replace("-", "");
  if (!final[newKey]) final[newKey] = [];
  final[newKey].push({href: current.href, id: current.id});
  return final;
}, {})

console.log(converted)