最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Renaming keys in javascript array - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Nov 26, 2014 at 20:34 ma_adma_ad 131 gold badge1 silver badge3 bronze badges 1
  • Javascript basics here. The {"a1": "example1"} syntax is a Javascript object, NOT an array. – jfriend00 Commented Nov 26, 2014 at 20:37
Add a ment  | 

1 Answer 1

Reset to default 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]]);
}
发布评论

评论列表(0)

  1. 暂无评论