开发者问题收集

根据另一个对象创建一个新的 javascript 对象

2020-06-25
75

我正在尝试创建一个新的 javascript 对象,该对象将具有基于另一个对象的新键名。我快完成了,但我的代码在行 // 失败此处 处失败,并出现 Uncaught TypeError: Cannot set property 'name' of undefined 。有什么想法可以解决此问题吗?此外,在这种情况下是否有更有效的方法来构建新对象?我需要它在较旧的 IE 浏览器上运行,因此采用这种方法。

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); 
3个回答

只需更改以下代码片段中的行

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);
RacoonOnMoon
2020-06-25
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...等等,这是无效的。

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

Shreyash bhatt
2020-06-25

您可以获取密钥,迭代它们并复制项目,如下所示:

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]);
Lajos Arpad
2020-06-25