简体   繁体   English

如何替换对象内部的属性名称? 使用Javascript

[英]How can I replace property names inside of an object? Javascript

My task is to create a function that swaps the names inside of the object with the names inside of an array. 我的任务是创建一个函数,该函数将对象内部的名称与数组内部的名称交换。 Daniel's name should change to Felix and his age should remain the same. 丹尼尔(Daniel)的名字应该改为菲利克斯(Felix),并且他的年龄应该保持不变。 In the end, the object should look like this. 最后,对象应如下所示。

{Felix:18,Carlos:21,Sasha:22,John:20}

From This 由此

{Daniel:18,Tyler:21,Michelle:22,Austin:20}

Heres what I have so far. 这是我到目前为止所拥有的。 I am new to programming so please try to take it easy on me. 我是编程的新手,所以请尝试轻松一点。

function swapNames(oldNames,newNames){
  for(var i in oldNames) {
    for(var k = 0; k < newNames.length; k++) {
      i = newNames[k];
  }
}
  console.log(i)
}

swapNames({Daniel:18,Tyler:21,Michelle:22,Austin:20}, 
["Felix","Carlos","Sasha","John"])

I thought this would loop through the object and the array and set the objects property name to the current string I am on. 我认为这会遍历对象和数组,并将对象的属性名称设置为当前所在的字符串。 But when I console.log() the object is exactly the same. 但是当我console.log()时,对象是完全相同的。

Here is what you could do. 这是您可以做的。

 const swapNames = (inputObj, outputNames) => { const output = {}; Object.keys(inputObj).forEach((key, index) => { output[outputNames[index]] = inputObj[key]; }); return output; } console.log(swapNames({ Daniel: 18, Tyler: 21, Michelle: 22, Austin: 20 }, ["Felix", "Carlos", "Sasha", "John"])); 

I don't want give away the answer, but your problem is here 我不想放弃答案,但是您的问题在这里

for(var i in oldNames) {
    // when i = Daniel;
    for(var k = 0; k < newNames.length; k++) {
      i = newNames[k];
      // you loop here keep change i from Daniel to "Felix","Carlos","Sasha","John", 
      // then you go back to above loop and repeat this, so all four old name got stuck with John 
    }

    console.log(i)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM