1

Lets say i want to change the key "c3" to a variable x = "b2" and keep the value of the key itself, so it should look like this: "b2": "example3".

var x = {
                "a1": "example1",
                "b2": "example2",
                "c3": "example3"
        };

Also, are there "better" types of arrays, that would go through all keys in this array just fine with a

for ( var a in x ) loop?

1
  • Javascript basics here. The {"a1": "example1"} syntax is a Javascript object, NOT an array. Commented Nov 26, 2014 at 20:37

1 Answer 1

9

You cannot change the value of a key in javascript object. Instead, you can assign a new key and then remove the prior key:

var x = {
    "a1": "example1",
    "b2": "example2",
    "c3": "example3"
};

// assign new key with value of prior key
x["a2"] = x["a1"];

// remove prior key
delete x["a1"];

And, please understand that these are NOT arrays. These are Javascript objects. An array is a different type of data structure.

The syntax for (var key in x) is the usual way to iterate properties of an object. Here's a summary of several different approaches:

// iterate all enumerable properties, including any on the prototype
for (var key in x) {
    console.log(key +", " + x[key]);
}

// iterate all enumerable properties, directly on the object (not on the prototype)
for (var key in x) {
    if (x.hasOwnProperty(key)) {
        console.log(key +", " + x[key]);
    }
}

// get an array of the keys and enumerate that
var keys = Object.keys(x);
for (var i = 0; i < keys.length; i++) {
    console.log(keys[i] +", " + x[keys[i]]);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.