Problem: given an object where some properties have keys starting with an arbitrary prefix, we want to transform it so that the corresponding properties are grouped under a prefix-key, and the original keys are renamed to drop the prefix.
Use case: js2xmlparser transforms JSON to XML. Object properties under a @
key (by default) are output as XML attributes.
Source (data):
{
"@id": 144,
"@pk": 111,
"title": "Robino",
"@year": 1971
}
Target:
{
"@":
{
"pk": 111,
"id": 144,
"year": 1971
},
"title": "Robino"
}
Expression:
_(data).reduce(
(acc, v, k, obj) =>
_.startsWith(k, "@")
? _.assign(acc, {
"@": _.assign(
acc["@"],
_(obj)
.pick(k)
.mapKeys((v, k) => _.tail(k).join(""))
.value()
)
})
: _.assign(acc, _.pick(obj, k)),
{}
);