Consider this definition object:
var map = {
'Username':
{
'user-name': 'userName',
'first-name': 'fName',
'last-name': 'lName',
'active': 'isActive'
}
}
How can I remap an object, for instance, this:
data:
{
'user-name': SamN,
'first-name': Sam,
'last-name': Norbert,
'active': 1
}
to get an output like this:
data:
{
'userName': SamN,
'fName': Sam,
'lName': Norbert,
'isActive': 1
}
Consider this definition object:
var map = {
'Username':
{
'user-name': 'userName',
'first-name': 'fName',
'last-name': 'lName',
'active': 'isActive'
}
}
How can I remap an object, for instance, this:
data:
{
'user-name': SamN,
'first-name': Sam,
'last-name': Norbert,
'active': 1
}
to get an output like this:
data:
{
'userName': SamN,
'fName': Sam,
'lName': Norbert,
'isActive': 1
}
Share
Improve this question
asked Jul 24, 2011 at 17:03
HyderAHyderA
21.5k48 gold badges116 silver badges183 bronze badges
2 Answers
Reset to default 7Simply iterate over the properties:
for(var prop in data) {
if(data.hasOwnProperty(prop) && prop in map.Username) {
data[map.Username[prop]] = data[prop];
delete data[prop];
}
}
This changes the object in-place. If you want to create a new object, just set the properties on a new empty object.
You can also iterate over the properties of map.Username
instead.
const map = {
'Username':
{
'user-name': 'userName',
'first-name': 'fName',
'last-name': 'lName',
'active': 'isActive'
}
}
const newObj = {};
const oldObj = { 'user-name': 'SamN', 'first-name': 'Sam', 'last-name': 'Norbert', 'active': 1 };
// Solution
Object.keys(oldObj).map((v, k) => {
newObj[map.Username[v]] = v
})
console.log(newObj) // {userName: "user-name", fName: "first-name", lName: "last-name", isActive: "active"}