Page 1 of 1

How to change key in JS object

Posted: 30 Oct 2020, 06:15
by Marius
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"
};

How to change key in JS object

Posted: 30 Oct 2020, 07:43
by Admin
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);