[英]Dynamically add or update key value on nested javascript array or object
Maybe I'm not putting in the correct search terms, because I can't find what I want, but I'd like to do something like the below in javascript. 也许我输入的搜索词不正确,因为找不到我想要的东西,但是我想在javascript中执行以下操作。 I believe the issue could be that I'm trying to dynamically create and assign a value to an array in one call which might not be allowed, or maybe my syntax is just wrong (I come from a PHP background).
我认为问题可能是我试图在一个调用中动态创建一个数组并为其赋值,但这可能是不允许的,或者我的语法是错误的(我来自PHP背景)。
var array = [];
array[key][] = value;
return array;
I'm looping through an existing array, and every time I come across a key, I want to add its associated value to a new array under that key. 我正在遍历一个现有数组,每次遇到一个键时,我想将其关联值添加到该键下的新数组中。 If
array[key]
doesn't exist yet I want it to be created. 如果
array[key]
不存在,我希望创建它。 If it already exists I want a new value to be added to the existing array[key]
. 如果已经存在,我希望将新值添加到现有
array[key]
。 I would like the end result to look something like this: 我希望最终结果看起来像这样:
array = [
[key1] = [value1, value2, value3, value4],
[key2] = [value1, value2, value3, value4],
...
]
It doesn't have to be an array. 它不必是数组。 It can be an object.
它可以是一个对象。
Demo code as below: 演示代码如下:
var array = [];
function pushToArray(key, value){
var subArray = array[key];
if( typeof subArray == "undefined"){
subArray = [];
array[key] = subArray;
}
subArray.push(value);
return subArray;
}
pushToArray("key1", "value11");
pushToArray("key1", "value12");
pushToArray("key2", "value21");
pushToArray("key2", "value22");
console.log(array);
You can use Array to do it, but it looks like Map is what you are looking for? 您可以使用Array来执行此操作,但看起来Map正是您想要的? The keys can be stored as Map's key, while for map's object, you can store the Array Objects.
这些键可以存储为Map的键,而对于map的对象,则可以存储数组对象。
Check out this link Javascripy Map Object 看看这个链接Javascripy Map Object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.