0

I'm new to javascript and have a question : i want to change keys if their value is number for example. What's wrong with my code?

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

function change(obj) {
    for (var prop in obj) {
        if (typeof obj[prop] === "number") {
            prop = "is number";
        }
    }
}

change(order);
console.log(order);

i want output to be

    is number : 100,
    is number : 200,
    is number: 300,
    whisky : "not in stock"
Max M
  • 1
  • 3

2 Answers2

0

When you do this

prop = "is number";

It is assigning "is number" to a variable called "prop". If you want to change the key, delete the existing key and create a new one.

Also, the keys are unique in an object. you cannot have multiple keys with same name.

function change(obj) {
    for (var prop in obj) {
        if (typeof obj[prop] === "number") {
            obj["is number"] = obj[prop];
            delete obj[prop];
        }
    }
}
krish
  • 40
  • 2
0

To change a key if it's value is a number, you need to clone the key and value first. And then you need to delete the key in the object and once it's deleted it should be injected into the object again.

`function change(obj) {
    for (var prop in obj) {
        if (typeof obj[prop] === "number") {
            obj['is_number_' + obj[prop]] = obj[prop]
            delete obj[prop]
        }
    }
}`

The result should be like this : is_number_100 : 100, is_number_200 : 200, is_number_300 : 300, whisky : "not in stock"

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
web-sudo
  • 701
  • 2
  • 13