by Sudipta Deb | Mar 31, 2021 | deserialize, javascript, JSON, parse, serialize, stringify
JSON (JavaScript Object Notation) is a way to represent data through text. It exists as a String and it supports all the basic data types that are supported by a standard JavaScript object. As per Wikipedia, the definition goes –
JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/; also /ˈdʒeɪˌsɒn/) is an open standard file format, and data interchange format, that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value).
Reference: https://en.wikipedia.org/wiki/JSON
Note – I am putting my JavaScript Developer study notes here.
There are two methods that I will be discussing in this post.
JSON.parse()
This method is used to deserialize or convert a JSON string into a JavaScript object. This is highly used while accessing the external API/server response. In the below example, I am converting a string to a JavaScript object using the parse method. You can use the dot (.) to access the individual items in the object.
Code:
const jsonString = `
{
“name”:”Sudipta Deb”,
“country”:”Canada”,
“favouriteCars”:[
“Honda”,”BMW”
],
“employed”:true
}
`;
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);
console.log(jsonObject.name);
Output:
{
name: ‘Sudipta Deb’,
country: ‘Canada’,
favouriteCars: [ ‘Honda’, ‘BMW’ ],
employed: true
}
JSON.stringify()
This method is used to serialize or convert a JavaScript object into a JSON string. This is highly used before transferring data to an external API/server. In the below example, I am converting the above JavaScript object to a string using the stringify method.
Code:
const jsonString = `
{
“name”:”Sudipta Deb”,
“country”:”Canada”,
“favouriteCars”:[
“Honda”,”BMW”
],
“employed”:true
}
`;
const jsonObject = JSON.parse(jsonString);
const jsonAsSerialized = JSON.stringify(jsonObject);
console.log(jsonAsSerialized);
Output:
{“name”:”Sudipta Deb”,”country”:”Canada”,”favouriteCars”:[“Honda”,”BMW”],”employed”:true}
Here is the youtube video
by Sudipta Deb | Mar 31, 2021 | array, Certification, javascript, Salesforce Certification, Sort
Like any programming language, JavaScript also provides ways to sort arrays. Different JavaScript engines implement this method using different sort algorithms. For example –
- Safari: Quicksort, Merge Sort, or Selection Sort
- V8: Quicksort, or Insertion Sort
- Firefox: Merge Sort
But in reality, it doesn’t really matter much as long as the arrays are getting sorted.
Note – I am putting my JavaScript Developer study notes
here.
The prototype for Sort method available in Array class is:
Array.sort([compareFunction])
Normally a callback function is passed which makes the sorting logic i.e. how the two numbers will be compared. This callback function should take two parameters i.e. param1 and param2 and works like this –
- callback function will return zero when both param1 and param2 are treated as equal
- callback function will return 1 when both param1 is smaller than param2
- callback function will return 11 when both param2 is smaller than param1
Note – In default sorting, param1 and param2 are always converted into Strings and then they will be sorted alphabetically.
For example, if we consider the below example
let numbers = [100, 23, 45, 12, 99];
let sortedNumbers = numbers.sort();
console.log(sortedNumbers);
Output:
[ 100, 12, 23, 45, 99 ]
But that’s not the correct sorting. The reason behind is that numbers here are converted into Strings and then sorted alphabetically due to default sorting.
To solve this we need to pass the callback function which will define the comparison logic. Below is the modified code –
let numbers = [100, 23, 45, 12, 99];
let sortedNumbers = numbers.sort((num1, num2) => num1 – num2);
console.log(sortedNumbers);
Output:
[ 12, 23, 45, 99, 100 ]
Sorting Array of objects
We can use the callback function to define the sort criteria while dealing with the objects as well.
For example, consider the below object, where we are using the sort method to sort array of employees based on their employee numbers.
let employee = [
{ name: “Robert”, empNumber: “98” },
{ name: “Kelly”, empNumber: “12” },
{ name: “Shane”, empNumber: “56” },
{ name: “James”, empNumber: “18” },
];
//Sorting based on empNumber
let sortedEmployeed = employee.sort(
(emp1, emp2) => emp1.empNumber – emp2.empNumber
);
console.log(sortedEmployeed);
Output:
[
{ name: ‘Kelly’, empNumber: ’12’ },
{ name: ‘James’, empNumber: ’18’ },
{ name: ‘Shane’, empNumber: ’56’ },
{ name: ‘Robert’, empNumber: ’98’ }
]
I have prepared a small video explaining the sort method which is below –
by Sudipta Deb | Mar 30, 2021 | javascript, REST, Web Technology
This blog post will cover the concepts of Arrays in JavaScript and different ways to manipulate Arrays in JavaScript.
Introduction
Objects normally allow to store keyed collection of values, but when it is required to store ordered collection, then JavaScript will come into the picture. JavaScript Array is a special variable, which can hold more than one value (of different types) at a time.
Declaration
There are basically two syntaxes for creating an empty array.
//Option 1
var names = [“James”, “Robert”, “Shane”];
//Option 2
var names;
names = [“James”, “Robert”, “Shane”];
Navigation
Below are the different ways to iterate through the array using indexes.
var names = [“James”, “Robert”, “Shane”];
//Option 1
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
//Option 2
for (let singleName of names) {
console.log(singleName);
}
//Option 3
for (let index in names) {
console.log(names[index]);
}
//Option 4
names.forEach((singleName) => {
console.log(singleName.toUpperCase());
});
Finding Array Elements
Below methods are mainly used to find elements in Array.
includes()
This method will return true if the specified value is present in the array, otherwise, it will pass false.
Code snippet:
function checkFruits(fruitName) {
let fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
return fruits.includes(fruitName);
}
console.log(“Includes Banana: “ + checkFruits(“Banana”));
console.log(“Includes Grape: “ + checkFruits(“Grape”));
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
Includes Banana: true
Includes Grape: false
indexOf()
This method will return the first index of the specified value if the specified value is present in the array, otherwise, it will return -1.
Code snippet:
function checkFruits(fruitName) {
let fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
return fruits.indexOf(fruitName);
}
console.log(“indexOf Apple: “ + checkFruits(“Apple”));
console.log(“indexOf Grape: “ + checkFruits(“Grape”));
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
indexOf Apple: 2
indexOf Grape: -1
lastIndexOf()
This method will return the last index of the specified value if the specified value is present in the array, otherwise, it will return -1.
Code snippet:
function checkFruits(fruitName) {
let fruits = [“Banana”, “Orange”, “Apple”, “Mango”, “Apple”, “Banana”];
return fruits.lastIndexOf(fruitName);
}
console.log(“lastIndexOf Apple: “ + checkFruits(“Apple”));
console.log(“lastIndexOf Banana: “ + checkFruits(“Banana”));
console.log(“lastIndexOf Grape: “ + checkFruits(“Grape”));
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
lastIndexOf Apple: 4
lastIndexOf Banana: 5
lastIndexOf Grape: -1
findIndex()
This method will return the index of the first element which satisfies the condition, otherwise, it will return -1.
Code snippet:
function checkAmountGreaterThan(value) {
let amount = [12, 25, 78, 29, 76, 98, 105];
return amount.findIndex((singleAmount) => singleAmount > value);
}
console.log(
“findIndex where amount is greater than 50: “ + checkAmountGreaterThan(50)
);
console.log(
“findIndex where amount is greater than 100: “ + checkAmountGreaterThan(100)
);
console.log(
“findIndex where amount is greater than 500: “ + checkAmountGreaterThan(500)
);
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
findIndex where amount is greater than 50: 2
findIndex where amount is greater than 100: 6
findIndex where amount is greater than 500: -1
find()
This method will return the value of the first element which satisfies the condition, otherwise, it will return undefined.
Code snippet:
function checkAmountGreaterThan(value) {
let amount = [12, 25, 78, 29, 76, 98, 105];
return amount.find((singleAmount) => singleAmount > value);
}
console.log(
“find where amount is greater than 50: “ + checkAmountGreaterThan(50)
);
console.log(
“find where amount is greater than 100: “ + checkAmountGreaterThan(100)
);
console.log(
“find where amount is greater than 500: “ + checkAmountGreaterThan(500)
);
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
find where amount is greater than 50: 78
find where amount is greater than 100: 105
find where amount is greater than 500: undefined
Merging/Joining Arrays
concat()
This method can be used to merge multiple arrays. It will return a new array with merged contents without modifying the original arrays.
Code snippet:
let country1 = [“India”, “Canada”, “Singapore”];
let country2 = [“Switzerland”, “United States of America”, “Norway”];
let mergedCountry = country1.concat(country2);
console.log(“mergedCountry: “ + mergedCountry);
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
mergedCountry: India,Canada,Singapore,Switzerland,United States of America,Norway
join()
This method can be used to join all the elements of the array separated by commas or the separator specified. It will return a new string without modifying the original arrays.
Code snippet:
let country = [
“India”,
“Canada”,
“Singapore”,
“Switzerland”,
“United States of America”,
“Norway”,
];
let joinedCountry = country.join(” <=> “);
console.log(“joinedCountry: “ + joinedCountry);
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
joinedCountry: India <=> Canada <=> Singapore <=> Switzerland <=> United States of America <=> Norway
Sort Arrays
sort()
This method can be used to sort elements of an array. By default, it will do the sorting in ascending order, but an optional parameter can be used to define the sort order. To understand sort method in details, please read the post –
Sorting Arrays in JavaScriptCode snippet:
let employees = [
{ name: “James Bond”, empNumber: 98 },
{ name: “Jacky Jones”, empNumber: 76 },
{ name: “Kelly Ditner”, empNumber: 24 },
{ name: “Jonathan Patel”, empNumber: 56 },
];
let sortEmployees1 = employees.sort();
console.log(“Printing sortEmployees1”);
sortEmployees1.forEach((singleEmployee) => {
console.log(
“Name: “ +
singleEmployee.name +
” Employee Number: “ +
singleEmployee.empNumber
);
});
let sortEmployees2 = employees.sort((a, b) => a.empNumber – b.empNumber);
console.log(“Printing sortEmployees2”);
sortEmployees2.forEach((singleEmployee) => {
console.log(
“Name: “ +
singleEmployee.name +
” Employee Number: “ +
singleEmployee.empNumber
);
});
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
Printing sortEmployees1
Name: James Bond Employee Number: 98
Name: Jacky Jones Employee Number: 76
Name: Kelly Ditner Employee Number: 24
Name: Jonathan Patel Employee Number: 56
Printing sortEmployees2
Name: Kelly Ditner Employee Number: 24
Name: Jonathan Patel Employee Number: 56
Name: Jacky Jones Employee Number: 76
Name: James Bond Employee Number: 98
reverse()
This method can be used to reverse the array by changing the original array. This method will return the reversed array.
Code snippet:
let employees = [
{ name: “James Bond”, empNumber: 98 },
{ name: “Jacky Jones”, empNumber: 76 },
{ name: “Kelly Ditner”, empNumber: 24 },
{ name: “Jonathan Patel”, empNumber: 56 },
];
let reverseEmployee = employees.reverse();
console.log(“Printing reverseEmployee”);
reverseEmployee.forEach((singleEmployee) => {
console.log(
“Name: “ +
singleEmployee.name +
” Employee Number: “ +
singleEmployee.empNumber
);
});
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
Printing reverseEmployee
Name: Jonathan Patel Employee Number: 56
Name: Kelly Ditner Employee Number: 24
Name: Jacky Jones Employee Number: 76
Name: James Bond Employee Number: 98
Advanced Functions
map()
This method will map each element of the array to something else. This method will require a callback function that will take three parameters (currentValue – this is mandatory, index and array). Finally, it will return an array.
Code snippet:
let employees = [
{ name: “James Bond”, empNumber: 98 },
{ name: “Jacky Jones”, empNumber: 76 },
{ name: “Kelly Ditner”, empNumber: 24 },
{ name: “Jonathan Patel”, empNumber: 56 },
];
const employeesInUpperCase = employees.map((singleEmployee) => {
return singleEmployee.name.toUpperCase();
});
console.log(“employeesInUpperCase: “ + employeesInUpperCase);
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
employeesInUpperCase: JAMES BOND,JACKY JONES,KELLY DITNER,JONATHAN PATEL
filter()
This method will test each element of the array with the filter criteria. This method will require a callback function that will take three parameters (currentValue – this is mandatory, index and array). Finally, it will return an array.
Code snippet:
let employees = [
{ name: “James Bond”, empNumber: 98 },
{ name: “Jacky Jones”, empNumber: 76 },
{ name: “Kelly Ditner”, empNumber: 24 },
{ name: “Jonathan Patel”, empNumber: 56 },
];
const filterEmployee = employees.filter((singleEmployee) => {
return singleEmployee.empNumber >= 50;
});
filterEmployee.forEach((singleEmployee) =>
console.log(
“Name: “ + singleEmployee.name + ” EmplNumber: “ + singleEmployee.empNumber
)
);
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
Name: James Bond EmplNumber: 98
Name: Jacky Jones EmplNumber: 76
Name: Jonathan Patel EmplNumber: 56
reduce()
This method will work on each element of the array and reduce it to one single value based on the logic written in the callback function. This method will require a callback function that will take two parameters (accumulator and currentValue), then the second parameter is the current index or initial value of the accumulator and the final parameter is the array. Finally, it will return an array.
Code snippet:
let employees = [
{ name: “James Bond”, expense: 98 },
{ name: “Jacky Jones”, expense: 76 },
{ name: “Kelly Ditner”, expense: 24 },
{ name: “Jonathan Patel”, expense: 56 },
];
let totalExpense = employees.reduce((accumulator, currentValue) => {
return accumulator + currentValue.expense;
}, 0);
console.log(“totalExpense: “ + totalExpense);
let words = [“Hello”, “Canada”, “How”, “are”, “you”, “?”];
let sentence = words.reduce(
(accumulator, currentValue) => accumulator + ” “ + currentValue
);
console.log(“sentence: “ + sentence);
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
totalExpense: 254
sentence: Hello Canada How are you ?
flat()
This method will work on subarrays and flatten them to make them a single array. You can specify the depth of flattening as an argument for the flat method.
Code snippet:
let numbers1 = [10, 34, 67, [1, 23, 12]];
let flattenNumbers1 = numbers1.flat();
console.log(flattenNumbers1);
let numbers2 = [10, 34, 67, [1, 23, 12, [56, 78, 100]]];
let flattenNumbers2 = numbers2.flat(2);
console.log(flattenNumbers2);
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
[ 10, 34, 67, 1, 23, 12 ]
[ 10, 34, 67, 1, 23, 12, 56, 78, 100 ]
every()
This method will work on every element of the array and will return true or false based on whether every element passes the condition mentioned.
Code snippet:
let numbers1 = [10, 34, 67, 1, 23, 12];
console.log(numbers1.every((singleNumber) => singleNumber > 0));
console.log(numbers1.every((singleNumber) => singleNumber > 10));
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
true
false
some()
This method will work on every element of the array and will return true or false based on whether at least one element passes the condition mentioned.
Code snippet:
let numbers1 = [10, 34, 67, 1, 23, 12];
console.log(numbers1.some((singleNumber) => singleNumber > 200));
console.log(numbers1.some((singleNumber) => singleNumber > 50));
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
false
true
spread()
This operator allows an iterable such as an array expression or string to expand where the number of arguments expected is dynamic. It can be 0, 1, or 100. It is mostly used in variable arrays.
Code snippet:
function doSum(a, b, c) {
return a + b + c;
}
let numbers = [1, 4, 5, 8, 2];
console.log(doSum(…numbers));
Console:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
10
rest()
Rest is the way to handle function parameters, allowing more easily to handle various inputs as parameters in the function. The syntax is the same as spread.
Code snippet:
function doSum(…args) {
let sum = args.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
return sum;
}
console.log(doSum(1, 4, 5, 8, 2));
Output:
[Running] node “/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js”
20
by Sudipta Deb | Mar 26, 2021 | Advanced Apex, Apex, Custom Metadata, Framework, Kitchener Developer Group, Trigger
Special thanks to our speaker, Mitchell Spano, for the session on “Orchestrate ALL of your Salesforce Automation with the Trigger Action Framework“.
You can register for all the upcoming sessions from the Kitchener Developer Group here.
You can get details (presentation and recording) of all the earlier sessions from the Kitchener Developer Group here.
Presentation:
by Sudipta Deb | Mar 19, 2021 | Heroku, heroku-connect, integration, Kitchener Developer Group, Kitchener User Group, Salesforce
Special thanks to our speaker, Julian Duque, for the session on “Let’s Learn about Heroku and How to Integrate with Salesforce“.
You can register for all the upcoming sessions from the Kitchener Developer Group here.
You can get details (presentation and recording) of all the earlier sessions from the Kitchener Developer Group here.
Presentation: