简体   繁体   中英

How can I add key : value to an object only if key does not already exist? If key exists already then edit value

I'm taking a list from a plain text file like this:

2: B D E
5: B C

and using javascript (with no plug-ins) to rearrange the list like this

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 />" );

            } 

        }

the above code will write:

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

which is close but I'm trying to check the property of truck if it is equal to tractor just append the trailer

everything I try the truck property is undefined

I've tried

truck [ tractor ] = trailer;

if (tractor in truck) { // never is

how can I get the value of truck [ tractor ] to see what I need to do next?

I am thinking you mean your output should be as follows:

given this:

2: B D E
5: B C

you want:

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

Here is a shorter, simplified version:

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

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