简体   繁体   English

重命名javascript数组中的键

[英]Renaming keys in javascript array

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". 假设我想将键“ c3”更改为变量x =“ b2”,并保留键本身的值,因此它应如下所示:“ 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? for(var a in x)循环?

You cannot change the value of a key in javascript object. 您无法在javascript对象中更改键的值。 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. 这些是Javascript对象。 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. for (var key in x)的语法是迭代对象属性的常用方法。 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]]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM