JavaScript:用数组替换对象键

时间:2017-08-12 20:49:12

标签: javascript

我是JS的新手并且正在尝试这些事情。我有以下对象:

 var array = ['First Name', 'age', 'country']

如何使用以下数组切换此对象的键?

{'First Name': 'john', 'age': 18, 'country': 'USA'}

看下面的内容:

using(SQLConnection con = new SQLConnection())
{
     //Get all the departments
     List<Department> departmentList = sp.GetAllDeparments();

     foreach(Deparment deparment in departmentList){

     //Get all employees
     List<Employee> employeeList= sp.GetEmployeesByDepartment(departmentId);

      foreach(Employee employee in employeeList){

            //Get all locations
            List<Location> locationList= sp.GetLocationsByEmployee(employeeId);

            foreach(Location location in locationList){
                  //Code for location generation for PDF. 
            }
       }
    }
}

6 个答案:

答案 0 :(得分:4)

重命名对象键的唯一方法是将旧键的值分配给新键,然后删除旧键

Object[ new_key ] = Object[ old_key ];
delete Object[ old_key ];

另一种方法是创建一个全新的对象(使用新键),将值分配给新键,然后删除旧对象。

答案 1 :(得分:1)

您可以使用Object.assign()Object.entries().map(),spread元素和计算属性将属性名称分配给具有当前属性索引值的新对象,迭代中的值,将原始对象的标识符设置为Object.assign()调用

的结果

let array = ['First Name', 'age', 'country']
let data = {'name': 'john', 'old': 18, 'place': 'USA'}

data = Object.assign({}, ...Object.entries(data)
         .map(([, prop], index) => ({[array[index]]: prop})));
            
console.log(data);

答案 2 :(得分:1)

&#13;
&#13;
var array = ['First Name', 'age', 'country'];

var data = {'name': 'john', 'old': 18, 'place': 'USA'};

var keys = Object.keys(data);
var newData = {};

for (var a in array) {
   //using new obj
   newData[array[a]] = data[keys[a]];

   //editing same obj
   data[array[a]] = data[keys[a]];
   delete data[keys[a]];
}

console.log(data);
console.log(newData);
&#13;
&#13;
&#13;

&#13;
&#13;
var array = ['First Name', 'age', 'country'];

var list = [
    { 'name': 'john 1', 'old': 18, 'place': 'USA' },
    { 'name': 'john 2', 'old': 19, 'place': 'USB' },
    { 'name': 'john 3', 'old': 20, 'place': 'USC' },
];

var newList = [];

for (var item in list) {
  var newData = {};
  
  for (var a in array) {
     newData[array[a]] = list[item][Object.keys(list[item])[a]];
  }
  
  newList.push(newData);
}

console.log(newList);
&#13;
&#13;
&#13;

答案 3 :(得分:1)

您可以使用带有替换键的对象并迭代它以更改键。

&#13;
&#13;
var data = { name: 'john', old: 18, place: 'USA' },
    newKeys = { name: 'First Name', old: 'age', place: 'country' };
    
Object.keys(newKeys).forEach(function (k) {
    data[newKeys[k]] = data[k];
    delete data[k];
});

console.log(data);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

而不是switching对象键;这是无法完成的,您必须删除密钥并添加新密钥,您只需使用所需的密钥创建一个新对象:

var data2 = {};
data2['First Name'] = data.name;
data2.age = data.old;
data2country = data.place;

答案 5 :(得分:0)

{{1}}

也许是一种功能性方法