简体   繁体   English

在JavaScript中将值附加到具有多个值的键

[英]Append value to key with multiple values in javascript

I have a textarea with structure like this: 我有一个像这样的文本区域:

1|title1|value2
1|title3|value4
1|...
3|title5|value6

My goal is to end up with a key-multiple value pair, such that I can output each value on demand (in a for loop) based on its order if I know the key. 我的目标是得到一个键-多个值对,这样,如果我知道键,就可以根据其顺序按需输出每个值(在for循环中)。

eg 例如

myArray[1][0][0] = title1
myArray[1][1][1] = value4
myArray[3][0][0] = title5

I can split up the textarea starting with something like this to create an object of lines, but it does not incorporate the third dimension of duplicate numbers. 我可以从这样的内容开始分割文本区域,以创建行对象,但是它不包含重复数字的第三维。

var audioArray = {};
var audioTextareaValue = document.getElementById('audioTextarea').value;
    audioTextareaValue.split('\n').forEach(function(x){
    var arr = x.split('|');
    arr[1] && (audioArray[arr[0]] = [arr[1],arr[2]]);
});

I think that you need to check if you already have the property on your audioArray (which is an object) and then push the new array to the list based on the key. 我认为您需要检查是否已经在audioArray(这是一个对象)上具有该属性,然后根据该键将新数组推入列表。

var audioDict = {};
var audioTextareaValue = document.getElementById('audioTextarea').value;

audioTextareaValue.split('\n').forEach(function(x){
   var arr = x.split('|');

   if ( !arr[0] ){
     return;
   }

   if (audioDict.hasOwnProperty(arr[0])) {
     audioDict[arr[0]].push([arr[1], arr[2]]);
   } else {
     audioDict[arr[0]] = [[arr[1], arr[2]]];
   }

});

demo on jsfiddle jsfiddle上的演示

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

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