i have an object
{
"name" : "foo",
"tag_name" : "grocery",
"tag_id" : "id",
"tag_nested_id" : "123",
}
I want the output as
{
"name" : "foo",
"tag" : {
"name" : "grocery",
"id" : "id",
"nested" : {
"id" : "123"
}
}
}
Is there any easy way to achieve this using lodash/underscore?
CodePudding user response:
No external libraries required, vanilla JS split on _
and .reduce
const data = {
"name" : "foo",
"tag_name" : "grocery",
"tag_id" : "id",
"tag_nested_id" : "123"
};
const result = Object.entries(data).reduce((object, [key, val]) => {
const splitKey = key.split('_');
const last = splitKey.pop();
splitKey.reduce((obj, x) => obj[x] ??= {}, object)[last] = val;
return object;
}, {})
console.log(JSON.stringify(result, null, 2));
CodePudding user response:
The answer by mani is as good as it gets, but with Underscore, we can create a version that is backwards compatible with older environments:
var data = {
"name" : "foo",
"tag_name" : "grocery",
"tag_id" : "id",
"tag_nested_id" : "123"
};
var result = _.reduce(data, function(object, val, key) {
var splitKey = key.split('_');
var last = splitKey.pop();
_.reduce(splitKey, function(obj, part) {
return obj[part] = obj[part] || {};
}, object)[last] = val;
return object;
}, {})
console.log(JSON.stringify(result, null, 2));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>