js/json

this insane language was developed by Brandon Eich in 10 days! John Resig showed a preview of what it is capable with his lib jQuery. All the new JS UI Frameworks are a testimony to the super powers it has.

Replace The Entire doc

var newDoc = document.open("text/html", "replace");
newDoc.write(myString);
newDoc.close();

01 | Object.assign & Clone JSON

const obj = {name: ‘tores’, male: true};
const newObj = Object.assign(obj, {name: ‘Totti’});
// this.obj’name'] => totti

cloneJSON(json): any {
  return JSON.parse(JSON.stringify(json));
}

02 | Add an element at the start of an array

// add an element at the start of a json array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Kiwi");
console.log("FRUITS:: " +JSON.stringify(fruits));

03 | Create Object Array with Code

// construct an Array of JSON Objects
var data = [1, 2, 3, 4, 5].map(el => {
  return {
    id: el,
    name: 'alpha',
    title: 'Mr.',
    description: 'laziest approach to constructing objs',
    age: (el * 10)
    };
});
console.log('::->' + JSON.stringify(data));

04 | Mutate Objects in a JSON

// initial JSON
var ips = {ipId1: {}, ipId2: {}};

// Solution1
Object.keys(ips).forEach(function(key) {
  ips[key] = {name: 'value', anotherName: 'another value'};
});

// Solution 2
Object.keys(ips).forEach(function(key) {
  Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});

Verify:

console.log(JSON.stringify(ips));

Prints:

{
  "ipId1": {
    "name":"value",
    "anotherName":"another value"
  },
  "ipId2": {
    "name":"value",
    "anotherName":"another value"
  }
}

05 | Truncate an Array

const arr = [201, 202, 103, 174, 255];

// truncates last 2 elements
arr.length = 3;
console.log(arr); //=> [11, 22, 33]

// clears the array
arr.length = 0;

06 | Match & Remove everything Beyond

// find a suggested item and remove everything below
var allAges = ["infant", "baby", "child", "adult"];
var suggested = "baby";
var index = allAges.findIndex(function(item, i){
  return item === suggested;
});

if(index = 0 && index < (allAges.length -1) ) {
  var trimAt = index + 1;
  allAges.length = trimAt;
}
console.log('Filtered::', allAges);

07 | Arrow Functions ES6

// Ex1:
var nums = [1, 4, 9];
var sqs = nums.map(Math.sqrt);

// Ex2:
myArray = [1,2,3,4];
myArray.map(element => {
  return element + 1;
});

// Above is same as
myArray.map(element => element + 1);

08 | remove duplicates

var names = ["Mike","Mike","Matt","Adam","Jenny"];
var uniqueNames = [];
var counter = 0;
$.each(names, function(i, el) {
    if($.inArray(el, uniqueNames) === -1) {
    	uniqueNames.push(el);
    } else {
    	console.log(i+'duplicate found: ' + el);
    }
});

console.log(uniqueNames);

09 | sort strings of numbers

var strNumbers = ["20","2500","10","35","0"];
var customSort = function (a, b) {
    return (Number(a.match(/(\d+)/g)[0]) - Number((b.match(/(\d+)/g)[0])));
}

var sorted = strNumbers.sort(customSort);
console.log(sorted);
document.getElementById("sorted").innerHTML= sorted;

// html
<div id="sorted"></div>

10 | JSON stringify vs parse

var obj = { name:"Adrian", age:28, city:"Melbourne"};
console.log(JSON.stringify(obj));
document.getElementById("demo").innerHTML = JSON.stringify(obj);

var json = '{"Foo":["B","A","R"]}';
var object = JSON.parse(json);

// html
<div id="demo"></div>

11 | Get number of chars in JSON response

the json payload it will be wrapped inside ‘pre’ tag when the browser renders it.

document.getElementsByTagName("pre")[0].innerHTML.length

/> JS Callback Function
pass a function as an argument

$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});

/> Abstract vs Strict Equality (== vs ===) in JS
In JS you have to use either == or === for comparison. First is known as abstract equality it will resolve the data type and compare the values for you. Second is known as strict equality it will first check if the type (ex: string, number, boolean etc) on the left hand side is same as the value being compared on the right hand side. Example:

console.log(4 == "4"); // true (abstract equality)
console.log(4 === "4"); // false (strict equality)

/> Concat | Minify | Uglify

Concatenation: appends all of the static files into one file (application.js).

Minification: removes unnecesary whitespace & redundant or optional tokens like semicolons & curly brackets. Can be reversed via a Linter.

Uglification: Transforms the code into an “unreadable” form, (i.e. renames variables, functions to hide the original names or intent). It can’t be reversed.

15 | Bubble Sort

console.log(sort([50, 10, 33, 3, 5, 20, 5]));

function sort(nums) {
  var n = nums.length;

  for(var i = 0; i < n; i++) {
  	for(var j = 1; j  nums[j]) {  

				var temp = nums[j-1];
        nums[j-1] = nums[j];
        nums[j] = temp;
      }
    }
  }

	return nums.toString();
}

16 | B64 String from image

loadImage(imageUrl) {
    const self = this;

    const xhr = new XMLHttpRequest();
    xhr.open('GET', imageUrl);
    // xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.responseType = 'blob';
    xhr.send();
    xhr.addEventListener('load', () => {
      const reader = new FileReader();
      reader.readAsDataURL(xhr.response);
      reader.addEventListener('loadend', function() {
        self.base64Img = reader.result.replace(/^data:image\/(png|jpg);base64,/, '');
        console.log('D O N E!', reader.result);
      });
    });
  }

/> Observer in JS

/> AJAX vs Promises vs Service Workers

Angular

/> Code Quality
Sonar Cube Istanbul

/> Angular Forms
Template Driven vs Model Driven

Template Driven approach is very familiar to Angular 1 developers and is ideal for easy migration of Angular 1 applications into Angular

Advertisements