LWC Tricks for using ES6

Telegram logo Join our Telegram Channel
#1 Iterate all elements in an array.
    array = [1,3,4,5,6,7];
    
    logAllFromArray(){
        this.array.forEach( element => {
            console.log('element =>' + element);
        });
    }
    Another way to iterate array elements.
    let array = [1, 3, 4, 5, 6, 7];
    for(let ele of array){
        console.log('ele => ' + ele);
    }
    

    #2 Use array.reduce to add all elements from the array.
      array = [1, 3, 4, 5, 6, 7];
      
      addAllFromArray() {
          let sum2 = this.array.reduce((sum, currentValue) => sum + currentValue);
          console.log('sum =>' + sum2);
      }

      #3 Iterate all keys in an Object
        let object = {a: 'a', b:'cc', c:'dd', d: '111'}
        for(let key in object){
            console.log('key =>' + key);
        }
        

        #4 Concatenate Arrays
        let array1 = ['a', 'b', 'c', 'c'];
        let array2 = [1, 2, 3, 4, 5];
        
        console.log('result => ' + array1.concat(array2));
        //result => a,b,c,c,1,2,3,4,5
        
        console.log('revers result => ' + array2.concat(array1));
        // revers result => 1,2,3,4,5,a,b,c,c
        
        console.log('another way => ' + [...array1, ...array2, ...['z', 'y', 'z']])
        // another way => a,b,c,c,1,2,3,4,5,z,y,z
        
        console.log('add into an empty array => ' + [].concat(array1, array2));
        // add into an empty array => a,b,c,c,1,2,3,4,5
        

        #5 Cloning
        let objectA = { firstName: 'Rahul', LastName: 'Gawale' };
        console.log('objectA => ' + JSON.stringify(objectA));
        // objectA => {"firstName":"Rahul","LastName":"Gawale"}
        
        let objectB = { ...objectA };
        objectB.gender = 'Male';
        console.log('objectB => ' + JSON.stringify(objectB));
        // objectB => {"firstName":"Rahul","LastName":"Gawale","gender":"Male"}
        
        // Deeplevel cloning for Muted Objects
        let newObject = JSON.parse(JSON.stringify(objectA));
        
        // clone the array
        let fruits = ['lemon', 'mango', 'jackfruit', 'orange'];
        let newArray = [...fruits];
        console.log('newArray => ' + newArray);
        // newArray => lemon,mango,jackfruit,orange
        

        No comments :
        Post a Comment

        Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com