user7400006
user7400006

Reputation: 117

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.

Upvotes: 0

Views: 57

Answers (2)

Yi Zhou
Yi Zhou

Reputation: 813

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

Upvotes: 1

Sreekanth
Sreekanth

Reputation: 3130

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"]));

Upvotes: 2

Related Questions