Thursday, January 23, 2020

Simple JaveScript Tricks with Array and Object

Combining Multiple Objects

Consider you have three different objects:
const obj1 = {'No': 1, 'firstname': 'Rakesh'};
const obj2 = {'lastname': 'Patel'};
const obj3 = {'Sex': 'Male','progLang':['.Net','MVC','SharePoint']};

combine all the above 3 object into another object:

const objCombined = {...obj1, ...obj2, ...obj3};

The '…' is the spread operator. You can read more about this in the MDN Web Docs

Check if an object is an array

const obj = {data: 1};
const arr = [1, 2, 3];

Array.isArray(obj);  // false
Array.isArray(arr);  // true

Rest parameter syntax

A function that accepts any number of arguments. There is a special syntax called the rest parameter syntax to create such a function.

Example 1:

function test(...values) {
    console.log(values);
}
test(1);
test(1, 2);
test(1, 2, 3);
test(1, 2, 3, 4);

output:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]

you can even pass object as a arguments

Example 2:

function sum(...values) {
    let sum = 0;
    for (let i = 0; i < values.length; i++) {
        sum += values[i];
    }
  
    return sum;
}

console.log(sum(1));
console.log(sum(1, 2));
console.log(sum(1, 2, 3));
console.log(sum(1, 2, 3, 4));

output:
1
3
6
10


No comments:

Post a Comment

Your feedback is always appreciated. I will try to reply to your queries as soon as time allows.Please don't spam,spam comments will be deleted upon reviews.