Reputation: 10828
The code is working as expected but is there a way to reduce the number of loops or improve the readability of this code to ES6/ES7 way? As you can see I am repeating the number of .split
and .join
It will convert Total.Subtotal": "10.50
into an array with the fields names and update string.
{
"Update": "+Total.+Subtotal = val:TotalSubtotal",
"Field": {
"+Total": "Total",
"+Subtotal": "Subtotal"
},
"Value": {
"val:TotalSubtotal": "10.50"
}
}
function createMap(val) {
const maps = [];
Object.keys(val).forEach(entry => {
const param = entry.split('.').join('');
const names = {};
for(const name of entry.split('.')) {
names[`+${name}`] = name;
}
const setName = Object.keys(names).join(".");
maps.push({
Update: `${setName} = val:${param}`,
Field: names,
Value: { [`val:${param}`]: val[entry] },
});
});
return maps;
}
console.log(
createMap({
"Total.Subtotal": "10.50"
})
)
Upvotes: 0
Views: 103
Reputation: 1229
A couple of ideas:
function createMap(val) {
return Object.keys(val).map(entry => {
const splitValues = entry.split('.');
const param = splitValues.join('');
const names = splitValues.reduce((obj, currentValue) => {
return { ...obj, [`+${currentValue}`]: currentValue };
}, {});
const setName = Object.keys(names).join('.');
return {
Update: `${setName} = val:${param}`,
Field: names,
Value: { [`val:${param}`]: val[entry] }
};
});
}
console.log(
createMap({
'Total.Subtotal': '10.50'
})
);
Upvotes: 1