在JavaScript关联数组中动态创建键

时间:2021-10-17 17:25:13

How can I dynamically create keys in javascript associative arrays?

如何在javascript关联数组中动态创建键?

All the documentation I've found so far is to update keys that are already created:

到目前为止,我找到的所有文档都是更新已经创建的键:

 arr['key'] = val;

I have a string like this " name = oscar "

我有一个字符串" name = oscar "

And I want to end up with something like this:

最后我想说的是

{ name: 'whatever' }

That is I split the string and get the first element, and I want to put that in a dictionary.

我分割字符串得到第一个元素,我想把它放到字典里。

Code

var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // prints nothing.

9 个解决方案

#1


126  

Use the first example. If the key doesn't exist it will be added.

使用第一个例子。如果键不存在,它将被添加。

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

Will pop up a message box containing 'oscar'.

将弹出一个包含“oscar”的消息框。

Try:

试一试:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );

#2


471  

Somehow all examples, while work well, are overcomplicated:

不知何故,所有的例子,虽然工作得很好,但都过于复杂:

  • They use new Array(), which is an overkill (and an overhead) for a simple associative array (AKA dictionary).
  • 它们使用new Array(),这是一个简单的关联数组(又称dictionary)的超杀(和开销)。
  • The better ones use new Object(). Works fine, but why all this extra typing?
  • 更好的方法是使用new Object()。很好,但是为什么要这么多打字呢?

This question is tagged "beginner", so let's make it simple.

这个问题被标记为“初学者”,所以让我们把它变得简单。

The uber-simple way to use a dictionary in JavaScript or "Why JavaScript doesn't have a special dictionary object?":

在JavaScript中使用字典的方法非常简单,或者“为什么JavaScript没有特殊的字典对象?”

// create an empty associative array (in JavaScript it is called ... Object)
var dict = {};   // huh? {} is a shortcut for "new Object()"

// add a key named fred with value 42
dict.fred = 42;  // we can do that because "fred" is a constant
                 // and conforms to id rules

// add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!";  // we use the subscript notation because
                           // the key is arbitrary (not id)

// add an arbitrary dynamic key with a dynamic value
var key = ..., // insanely complex calculations for the key
    val = ...; // insanely complex calculations for the value
dict[key] = val;

// read value of "fred"
val = dict.fred;

// read value of 2bob2
val = dict["2bob2"];

// read value of our cool secret key
val = dict[key];

Now let's change values:

现在让我们改变值:

// change the value of fred
dict.fred = "astra";
// the assignment creates and/or replaces key-value pairs

// change value of 2bob2
dict["2bob2"] = [1, 2, 3];  // any legal value can be used

// change value of our secret key
dict[key] = undefined;
// contrary to popular beliefs assigning "undefined" does not remove the key

// go over all keys and values in our dictionary
for (key in dict) {
  // for-in loop goes over all properties including inherited properties
  // let's use only our own properties
  if (dict.hasOwnProperty(key)) {
    console.log("key = " + key + ", value = " + dict[key]);
  }
}

Deleting values is easy too:

删除值也很容易:

// let's delete fred
delete dict.fred;
// fred is removed, the rest is still intact

// let's delete 2bob2
delete dict["2bob2"];

// let's delete our secret key
delete dict[key];

// now dict is empty

// let's replace it, recreating all original data
dict = {
  fred:    42,
  "2bob2": "twins!"
  // we can't add the original secret key because it was dynamic,
  // we can only add static keys
  // ...
  // oh well
  temp1:   val
};
// let's rename temp1 into our secret key:
if (key != "temp1") {
  dict[key] = dict.temp1; // copy the value
  delete dict.temp1;      // kill the old key
} else {
  // do nothing, we are good ;-)
}

#3


29  

Javascript does not have associative arrays, it has objects.

Javascript没有关联数组,它有对象。

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

下面几行代码都做了同样的事情——将对象上的“name”字段设置为“orion”。

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all, you're setting fields on the object.

看起来你有一个关联数组,因为数组也是一个对象——但是你根本没有在数组中添加东西,而是在对象上设置字段。

Now that that is cleared up, here is a working solution to your example

现在已经解决了这个问题,下面是您的示例的一个工作解决方案。

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// split into key and value
var kvp = cleaned.split('=');

// put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // prints oscar.

#4


9  

In response to MK_Dev, one is able to iterate, but not consecutively. (For that obviously an array is needed)

在响应MK_Dev时,可以迭代,但不是连续的。(显然需要一个数组)

Quick google search brings up hash tables in javascript

快速谷歌搜索将在javascript中显示哈希表

Example code for looping over values in a hash (from aforementioned link):

用于在散列中对值进行循环的示例代码(来自上述链接):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

#5


3  

Original Code (I added the line numbers so can refer to them):

原始代码(我添加了行号以便参考):

1  var text = ' name = oscar '
2  var dict = new Array();
3  var keyValuePair = text.split(' = ');
4  dict[ keyValuePair[0] ] = 'whatever';
5  alert( dict ); // prints nothing.

Almost there...

差不多了…

  • line 1: you should do a trim on text so it is name = oscar.
  • 第1行:您应该对文本进行修饰,使其为name = oscar。
  • line 3: okay as long as you ALWAYS have spaces around your equal. might be better to not trim in line 1, use = and trim each keyValuePair
  • 第3行:好吧,只要你在等号周围有空格。最好不要在第1行中进行修剪,使用=并修剪每个keyValuePair。
  • add a line after 3 and before 4:

    在3点之后和4点之前加一行:

    key = keyValuePair[0];`
    
  • line 4: Now becomes:

    第4行:现在就变成:

    dict[key] = keyValuePair[1];
    
  • line 5: Change to:

    第5行:改变:

    alert( dict['name'] );  // it will print out 'oscar'
    

What I'm trying to say is that the dict[keyValuePair[0]] does not work, you need to set a string to keyValuePair[0] and use that as the associative key. That is the only way I got mine to work. After you have set it up you can either refer to it with numeric index or key in quotes.

我想说的是,dict[keyValuePair[0]]不能工作,您需要将字符串设置为keyValuePair[0]并将其用作关联键。这是我唯一的工作方式。设置好之后,您可以用数字索引或引号中的键来引用它。

Hope that helps.

希望有帮助。

#6


2  

All modern browsers support a Map, which is a key/value data stricture. There are a couple of reasons that make using a Map better than Object:

所有现代浏览器都支持映射,这是一个键值数据限制。有几个原因使得使用地图比使用对象更好:

  • An Object has a prototype, so there are default keys in the map.
  • 一个对象有一个原型,所以在映射中有默认的键。
  • The keys of an Object are Strings, where they can be any value for a Map.
  • 对象的键是字符串,它们可以是映射的任何值。
  • You can get the size of a Map easily while you have to keep track of size for an Object.
  • 您可以很容易地获得地图的大小,同时您必须跟踪对象的大小。

Example:

例子:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

如果您想要从其他对象引用的键被垃圾收集,请考虑使用弱映射而不是Map。

#7


1  

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
// show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

this is ok but iterates through every property of the array object. if you want to only iterate through the properties myArray.one, myArray.two... you try like this

这是可以的,但是遍历数组对象的每个属性。如果您只想遍历属性myArray。1、myArray.two……你试着这样

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(i=0;i<maArray.length;i++{
    console.log(myArray[myArray[i]])
}

now you can access both by myArray["one"] and iterate only through these properties.

现在,您可以通过myArray[“1”]访问这两个属性,并仅通过这些属性进行迭代。

#8


1  

I think it is better if you just created like this

我认为你这样创作会更好

var arr = [];

arr = {
   key1: 'value1',
   key2:'value2'
};

for more info , take a look at this

要了解更多信息,请看这个

JavaScript Data Structures - Associative Array

JavaScript数据结构-关联数组

#9


1  

var obj = {};

                for (i = 0; i < data.length; i++) {
                    if(i%2==0) {
                        var left = data[i].substring(data[i].indexOf('.') + 1);
                        var right = data[i + 1].substring(data[i + 1].indexOf('.') + 1);

                        obj[left] = right;
                        count++;
                    }
                }
                console.log("obj");
                console.log(obj);
                // show the values stored
                for (var i in obj) {
                    console.log('key is: ' + i + ', value is: ' + obj[i]);
                }

            }
        };

}

}

#1


126  

Use the first example. If the key doesn't exist it will be added.

使用第一个例子。如果键不存在,它将被添加。

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

Will pop up a message box containing 'oscar'.

将弹出一个包含“oscar”的消息框。

Try:

试一试:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );

#2


471  

Somehow all examples, while work well, are overcomplicated:

不知何故,所有的例子,虽然工作得很好,但都过于复杂:

  • They use new Array(), which is an overkill (and an overhead) for a simple associative array (AKA dictionary).
  • 它们使用new Array(),这是一个简单的关联数组(又称dictionary)的超杀(和开销)。
  • The better ones use new Object(). Works fine, but why all this extra typing?
  • 更好的方法是使用new Object()。很好,但是为什么要这么多打字呢?

This question is tagged "beginner", so let's make it simple.

这个问题被标记为“初学者”,所以让我们把它变得简单。

The uber-simple way to use a dictionary in JavaScript or "Why JavaScript doesn't have a special dictionary object?":

在JavaScript中使用字典的方法非常简单,或者“为什么JavaScript没有特殊的字典对象?”

// create an empty associative array (in JavaScript it is called ... Object)
var dict = {};   // huh? {} is a shortcut for "new Object()"

// add a key named fred with value 42
dict.fred = 42;  // we can do that because "fred" is a constant
                 // and conforms to id rules

// add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!";  // we use the subscript notation because
                           // the key is arbitrary (not id)

// add an arbitrary dynamic key with a dynamic value
var key = ..., // insanely complex calculations for the key
    val = ...; // insanely complex calculations for the value
dict[key] = val;

// read value of "fred"
val = dict.fred;

// read value of 2bob2
val = dict["2bob2"];

// read value of our cool secret key
val = dict[key];

Now let's change values:

现在让我们改变值:

// change the value of fred
dict.fred = "astra";
// the assignment creates and/or replaces key-value pairs

// change value of 2bob2
dict["2bob2"] = [1, 2, 3];  // any legal value can be used

// change value of our secret key
dict[key] = undefined;
// contrary to popular beliefs assigning "undefined" does not remove the key

// go over all keys and values in our dictionary
for (key in dict) {
  // for-in loop goes over all properties including inherited properties
  // let's use only our own properties
  if (dict.hasOwnProperty(key)) {
    console.log("key = " + key + ", value = " + dict[key]);
  }
}

Deleting values is easy too:

删除值也很容易:

// let's delete fred
delete dict.fred;
// fred is removed, the rest is still intact

// let's delete 2bob2
delete dict["2bob2"];

// let's delete our secret key
delete dict[key];

// now dict is empty

// let's replace it, recreating all original data
dict = {
  fred:    42,
  "2bob2": "twins!"
  // we can't add the original secret key because it was dynamic,
  // we can only add static keys
  // ...
  // oh well
  temp1:   val
};
// let's rename temp1 into our secret key:
if (key != "temp1") {
  dict[key] = dict.temp1; // copy the value
  delete dict.temp1;      // kill the old key
} else {
  // do nothing, we are good ;-)
}

#3


29  

Javascript does not have associative arrays, it has objects.

Javascript没有关联数组,它有对象。

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

下面几行代码都做了同样的事情——将对象上的“name”字段设置为“orion”。

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all, you're setting fields on the object.

看起来你有一个关联数组,因为数组也是一个对象——但是你根本没有在数组中添加东西,而是在对象上设置字段。

Now that that is cleared up, here is a working solution to your example

现在已经解决了这个问题,下面是您的示例的一个工作解决方案。

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// split into key and value
var kvp = cleaned.split('=');

// put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // prints oscar.

#4


9  

In response to MK_Dev, one is able to iterate, but not consecutively. (For that obviously an array is needed)

在响应MK_Dev时,可以迭代,但不是连续的。(显然需要一个数组)

Quick google search brings up hash tables in javascript

快速谷歌搜索将在javascript中显示哈希表

Example code for looping over values in a hash (from aforementioned link):

用于在散列中对值进行循环的示例代码(来自上述链接):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

#5


3  

Original Code (I added the line numbers so can refer to them):

原始代码(我添加了行号以便参考):

1  var text = ' name = oscar '
2  var dict = new Array();
3  var keyValuePair = text.split(' = ');
4  dict[ keyValuePair[0] ] = 'whatever';
5  alert( dict ); // prints nothing.

Almost there...

差不多了…

  • line 1: you should do a trim on text so it is name = oscar.
  • 第1行:您应该对文本进行修饰,使其为name = oscar。
  • line 3: okay as long as you ALWAYS have spaces around your equal. might be better to not trim in line 1, use = and trim each keyValuePair
  • 第3行:好吧,只要你在等号周围有空格。最好不要在第1行中进行修剪,使用=并修剪每个keyValuePair。
  • add a line after 3 and before 4:

    在3点之后和4点之前加一行:

    key = keyValuePair[0];`
    
  • line 4: Now becomes:

    第4行:现在就变成:

    dict[key] = keyValuePair[1];
    
  • line 5: Change to:

    第5行:改变:

    alert( dict['name'] );  // it will print out 'oscar'
    

What I'm trying to say is that the dict[keyValuePair[0]] does not work, you need to set a string to keyValuePair[0] and use that as the associative key. That is the only way I got mine to work. After you have set it up you can either refer to it with numeric index or key in quotes.

我想说的是,dict[keyValuePair[0]]不能工作,您需要将字符串设置为keyValuePair[0]并将其用作关联键。这是我唯一的工作方式。设置好之后,您可以用数字索引或引号中的键来引用它。

Hope that helps.

希望有帮助。

#6


2  

All modern browsers support a Map, which is a key/value data stricture. There are a couple of reasons that make using a Map better than Object:

所有现代浏览器都支持映射,这是一个键值数据限制。有几个原因使得使用地图比使用对象更好:

  • An Object has a prototype, so there are default keys in the map.
  • 一个对象有一个原型,所以在映射中有默认的键。
  • The keys of an Object are Strings, where they can be any value for a Map.
  • 对象的键是字符串,它们可以是映射的任何值。
  • You can get the size of a Map easily while you have to keep track of size for an Object.
  • 您可以很容易地获得地图的大小,同时您必须跟踪对象的大小。

Example:

例子:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

如果您想要从其他对象引用的键被垃圾收集,请考虑使用弱映射而不是Map。

#7


1  

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
// show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

this is ok but iterates through every property of the array object. if you want to only iterate through the properties myArray.one, myArray.two... you try like this

这是可以的,但是遍历数组对象的每个属性。如果您只想遍历属性myArray。1、myArray.two……你试着这样

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(i=0;i<maArray.length;i++{
    console.log(myArray[myArray[i]])
}

now you can access both by myArray["one"] and iterate only through these properties.

现在,您可以通过myArray[“1”]访问这两个属性,并仅通过这些属性进行迭代。

#8


1  

I think it is better if you just created like this

我认为你这样创作会更好

var arr = [];

arr = {
   key1: 'value1',
   key2:'value2'
};

for more info , take a look at this

要了解更多信息,请看这个

JavaScript Data Structures - Associative Array

JavaScript数据结构-关联数组

#9


1  

var obj = {};

                for (i = 0; i < data.length; i++) {
                    if(i%2==0) {
                        var left = data[i].substring(data[i].indexOf('.') + 1);
                        var right = data[i + 1].substring(data[i + 1].indexOf('.') + 1);

                        obj[left] = right;
                        count++;
                    }
                }
                console.log("obj");
                console.log(obj);
                // show the values stored
                for (var i in obj) {
                    console.log('key is: ' + i + ', value is: ' + obj[i]);
                }

            }
        };

}

}