简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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