最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remapping object properties - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 7

Simply 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"}
发布评论

评论列表(0)

  1. 暂无评论