How to change key in JS object

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

How to change key in JS object

I have a question: i want to change keys into a JavaScript object if their value is number, for example, I have the following object:

Code: Select all

const order = {
  wine : 100,
  vodka : 200,
  beer : 300,
  whisky : "not in stock"
};
I want to get this result:

Code: Select all

const order = {
  is_nr_100 : 100,
  is_nr_200 : 200,
  is_nr_300 : 300,
  whisky : "not in stock"
};

Admin Posts: 805
To change a key into a JavaScript object, you need to clone the value with the new key, and then you delete the old key in the object.

Code: Select all

const order = {
  wine : 100,
  vodka : 200,
  beer : 300,
  whisky : "not in stock"
};

function changeKey(obj) {
  for (var prop in obj) {
    if (typeof obj[prop] === 'number') {
      obj['is_nr_' + obj[prop]] = obj[prop]
      delete obj[prop]
    }
  }
}

changeKey(order);
console.log(order);

Similar Topics