I need to convert
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},
];
to a hash map like this:
var converted = {
linksA: [
{href: 'url1', id: 0},
{href: 'url2', id: 1}
],
linksB: [
{href: 'url3', id: 2},
{href: 'url4', id: 3}
],
}
Not sure if it's doable with lodash
You don't even have to use lodash if you don't want to. The .reduce
array method should be sufficient:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.