只有当密钥不存在时,如何才能将key:value添加到对象?如果密钥已存在,则编辑值

时间:2014-11-15 18:49:02

标签: javascript arrays hashtable associative-array

我从这样的纯文本文件中获取列表:

2: B D E
5: B C

并使用javascript(没有插件)重新排列列表

B: 2 5
D: 2
E: 5


        // rest of code file input , etc. not necessary to list here, imho

        var contents = e.target.result; // read contents of file

        var oldParts = contents.split(/\n/); // put each line of contents into array

        for (i = 0; i < oldParts.length; i++) {

            var allChar = oldParts[i].split( ' ' ); // each character from the line

            var truck = {};

            var tractor = "";

            var trailer = "";

            for (j = 0; j < allChar.length; j++) { 

                allChar[j] = allChar[j].replace(":", ""); // remove the ":" delimiter

                allChar[j].trim();

                trailer = allChar[0]; // get just the numbers

                if ( isNaN ( allChar[j] ) ) { // is not a number

                    tractor = allChar[j];


                    if ( truck.hasOwnProperty(tractor) ) {

                        console.log ( "already in" );

                    } else { 

                        console.log ( " needs to be added" ) ;

                        truck [ tractor ] = trailer;

                    }

                }

            }


            for ( tractor in truck ) {

                document.write ( tractor + " : " + truck[tractor] + "<br />" );

            } 

        }

上面的代码将写:

B: 2
D: 2
E: 2
B: 5
C: 5

虽然很接近但我试图检查卡车的属性是否等于拖拉机只是附加预告片

我尝试卡车财产的一切都是未定义的

我已经尝试了

truck [ tractor ] = trailer;

if (tractor in truck) { // never is

如何才能获得卡车[拖拉机]的价值,看看我接下来需要做什么?

1 个答案:

答案 0 :(得分:0)

我在想你的意思是你的输出应该如下:

鉴于此:

2: B D E
5: B C

你想要:

B: 2 5
D: 2
E: 2
C: 5

这是一个简短的简化版本:

var data = "2: B D E\n5: B C";
var hashTable = {}, finalString = "";

var dataArray = data.split("\n");
dataArray.forEach(function(i){
  var tempArr = i.split(':');
  tempArr[1].split(' ').forEach(function(j){
    if([undefined, ''].indexOf(j) != -1) return;

    (j in hashTable ) ? hashTable[j].push(tempArr[0].trim()) : hashTable[j] = [tempArr[0]];
  })
});
(function(){
   for(var s in hashTable){
     finalString += s + ": " + hashTable[s].join(' ') + "\n";
   }
}())
console.log(finalString);
//B: 2 5
//D: 2
//E: 2
//C: 5