ECMAScript 2023, the 14th edition of the language, has some great changes that will make your programming life easier.
Thursday, November 30, 2023
Tuesday, December 14, 2021
Convert Number, String, Float and Format JSON
1) Convert to String
To quickly convert a number to a string, we can use the concatenation operator (+) plus followed by an empty set of quotation marks "" .
let val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"
2) Convert to Number
The opposite can be quickly achieved using the addition operator + .
let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"
This may also be used to convert Booleans to numbers, as below:
console.log(+true); // Return: 1
console.log(+false); // Return: 0
3)Quick Float to Integer
If you want to convert a float to an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there is also a faster way to truncate a float to an integer using |, the bitwise OR operator.
console.log(23.9 | 0); // Result: 23
console.log(-23.9 | 0); // Result: -23
4)Format JSON Code
Lastly, you may have used JSON.stringify before, but did you realise it can also help indent your JSON for you?
The stringify() method takes two optional parameters: a replacer function, which you can use to filter the JSON that is displayed, and a space value.
The space value takes an integer for the number of spaces you want or a string (such as '\t' to insert tabs), and it can make it a lot easier to read fetched JSON data.
console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
// "alpha": A,
// "beta": B
// }'
Wednesday, February 3, 2021
Simple way to find Index value from JSON Array
Simple way to find Index value from JSON Array
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var index = data.findIndex(obj => obj.name=="allInterests");
console.log(index);
Thursday, January 28, 2021
JavaScript to get index from a JSON object with value
In modern browsers you can use findIndex:
But this function is not supported by even not so old versions of a few browser as well as in IE (EDGE supports it). So below is a workaround using javascript: You can use either Array.forEach or Array.find or Array.filter
This method takes little more overhead as it loops through the whole object to search for the match. So, for lengthy JSON data, this method is not suggested(even though it gets the work done).
Tuesday, October 6, 2020
Thursday, September 10, 2020
Selecting distinct values from a JSON
eData is the JSON array
var items = eData.map((d)=> {return d.year})
var uniq = items.filter(GetUnique)
function GetUnique(value, index, self) {
return self.indexOf(value) === index;
}
Thursday, July 16, 2020
Monday, February 17, 2020
JSON Group by count, output to key value pair json result
Following is the JSON and need to manipulate it in format to groupBy.
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
Thursday, November 14, 2019
Wednesday, October 23, 2019
Sorting by Key in An Array of object with Jquery
{ TagId: 2, TagName: "Single Page Application", },
{ TagId: 3, TagName: "Visual Studio", },
{ TagId: 4, TagName: "Fakes", }]
var posts = [];
posts = sortByKeyDesc(data, "TagId");
function sortByKeyDesc(array, key) {
return array.sort(function (a, b) {
var x = a[key]; var y = b[key];
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
}
function sortByKeyAsc(array, key) {
return array.sort(function (a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
Tuesday, August 20, 2019
Convert JSON to CSV Format
//logData is the JSON object having json data, rest of the code do the job.
const items = logData
const replacer = (key, value) => value === null ? '' : value
const header = Object.keys(items[0])
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
console.log(csv)
Wednesday, July 3, 2019
Iterate/Loop over a JSON structure
var s = [{key:1,value:"abc"},{key:2,value:"def"},{key:3,value:"xyz"},{key:1,value:"pqr"}]
for(var i in s)
console.log ("Key :" + s[i].key + " - Value :" + s[i].value)
//Output
Key :1 - Value :abc
Key :2 - Value :def
Key :3 - Value :xyz
Key :1 - Value :pqr
Tuesday, June 18, 2019
How to use Filter with JSON Data
var jd = JSON.parse('[{"status":"Pass","Marks":98,"subject":"English"},{"status":"Pass","Marks":99,"subject":"Math"},{"status":"Fail","Marks":32,"subject":"Science"},{"status":"Fail","Marks":30,"subject":"History"},{"status":"Pass","Marks":95,"subject":"Computer"}]')
// use filter property to get each item with the condition match as Status as PASS (we are using === to validate they type and return if condition get true.)
var fd = jd.filter(function(item){
return (item.status === "Pass");
});
result will be.
fd = [{"status":"Pass","Marks":98,"subject":"English"},{"status":"Pass","Marks":99,"subject":"Math"},{"status":"Pass","Marks":95,"subject":"Computer"}]
Saturday, March 9, 2019
Simple way to Check if JSON is correct or not..
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Monday, February 25, 2019
Get index from a JSON object with value
// Google Chrome user.
var index = data.findIndex(obj => obj.name=="allInterests");
console.log(index);
// for IE user
var index = -1;
for (var i = 0; i < data.length; ++i) {
if (data[i].name == "allInterests") {
index = i;
break;
}
}
console.log(index);