简体   繁体   中英

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. 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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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