基于另一个对象创建一个新的javascript对象

时间:2020-06-25 07:30:20

标签: javascript

我正在尝试创建一个新的javascript对象,该对象将具有基于另一个对象的新键名。我快到了,但是我的代码在// fails here的{​​{1}}行中失败了。任何想法如何做到这一点?另外,在这种情况下,是否有更有效的方法来构建新对象?我需要它在较旧的IE浏览器上运行,因此需要这种方法。

Uncaught TypeError: Cannot set property 'name' of undefined 

3 个答案:

答案 0 :(得分:1)

只需更改下面的代码段中的行

originalObj = {"name":"John","age":30,"state":"CA","country":"USA"};
    
    objCodes = {"name":101,"age":102,"state":103,"country":104};
    
    // newObj = {101:"John", 102:30,103:"CA",104:"USA"};
        
    newObj = {};
    
    for (var i in originalObj) {
      if (objCodes.hasOwnProperty(i)) {
          // console.log(i, originalObj[i]);
          console.log(objCodes[i],originalObj[i])
          newObj[objCodes[i]] = originalObj[i] // fails here
          
        
       }
    }
    
    console.log(newObj);

答案 1 :(得分:1)

originalObj = {"name":"John","age":30,"state":"CA","country":"USA"};

objCodes = {"name":101,"age":102,"state":103,"country":104};

// newObj = {101:"John", 102:30,103:"CA",104:"USA"};
    
newObj = {};

for (var i in originalObj) {
  if (objCodes.hasOwnProperty(i)) {
      // console.log(i, originalObj[i]);
      console.log(objCodes[i],originalObj[i])
      newObj[objCodes[i]] = originalObj[i] // fails here
      
    
   }
}

console.log(newObj);

将点分符号更改为方括号符号。 这是JavaScript的原因,它只允许使用带点分符号的有效名称,而该名称不能以数字开头。并且在您的情况下,键设置为101,102 ...等等,这是无效的。

编辑:动态属性名称只能通过方括号表示法使用,例如在使用变量设置属性名称的情况下。

答案 2 :(得分:0)

您可以获取密钥,对其进行迭代并复制以下内容:

originalObj = {"name":"John","age":30,"state":"CA","country":"USA"};

objCodes = {"name":101,"age":102,"state":103,"country":104};

// newObj = {101:"John", 102:30,103:"CA",104:"USA"};
    
newObj = {};

Object.keys(objCodes).forEach(i => newObj[objCodes[i]] = originalObj[i]);