Ildar Akhmetov
Ildar Akhmetov

Reputation: 1431

Rename a subkey of an object with ES6

I have a JS object of the following structure:

let data = {
  Apples: {
    A: 2,
    B: 9
  },
  Oranges: {
    C: 4,
    D: 8
  },
  Bananas: {
    E: 3,
    F: 2
  },
  Peaches: {
    G: 8,
    H: 4
  },
  Pears: {
    I: 10,
    J: 10
  },
  Melons: {
    K: 4,
    L: 7
  }
};

I need to rename the subkey dynamically with JS.

For example, I need to rename the key A into New name. What is the best ES6-enabled way to do it?

I tried to loop through the object using a simple for loop and generate a new object with a renamed key, but it's indeed not the most efficient way!

Upvotes: 0

Views: 53

Answers (1)

Pablo CG
Pablo CG

Reputation: 816

What about this?

I'm not generating a new object, but adding the new properties to the existing one and deleting the original ones.

let data = {
  Apples: {
    A: 2,
    B: 9
  },
  Oranges: {
    C: 4,
    D: 8
  },
  Bananas: {
    E: 3,
    F: 2
  },
  Peaches: {
    G: 8,
    H: 4
  },
  Pears: {
    I: 10,
    J: 10
  },
  Melons: {
    K: 4,
    L: 7
  }
};

for (let key1 in data) {
  const e = data[key1];
  for (let key2 in e) {
    e["New Name for " + key2] = e[key2];
    delete e[key2];
  }
}

console.log(data);

Upvotes: 1

Related Questions