Working with JS Objects

This example shows how to iterate through a javascript object. Combine arrays, reduce the object

JSON Object with keys and value object

Let us first look at our json object that needs to be iterated. Pretty printing the json file with strigify.

JSON.stringify(obj, null, 2); // spacing level = 2
{
  "Sy": {"speed": 1.0054454,"rashi": 7 },
  "Ch": {"speed": 12.6783487,"rashi": 7 },
  "Ma": {"speed": 0.1587292,"rashi": 12 },
  "Bu": {"speed": 1.5975625,"rashi": 7 },
  "Gu": {"speed": -0.1278241,"rashi": 2 },
  "Sk": {"speed": 1.2191773,"rashi": 6 },
  "Sa": {"speed": 0.097599,"rashi": 9 },
  "Ra": {"speed": -0.0529538,"rashi": 11 },
  "Ke": {"speed": -0.0529538,"degree": 16.842893500000002 }
}

The above js object contains keys and the value are objects too.

Using loops

The usual way of accessign the object is using the traditional for loop

for(var g in obj){
    console.log(g)
}

Using forEach

Instead we can use foreach function.But before we can apply forEach function, we must make the json enumerable using Object.keys()

Object.keys(obj).forEach((k,v)=>{ 
    console.log(v)
})

Reduce function

Group an array of objects by key.

  • We are using a property in the value of the object map.
  • assigning property value as key value
  • grouping keys as values

In the below code, current value is an array with 2 values. e.g. ['Sy', {rashi: 7, speed: 1.0054454}]

Object.entries(obj).reduce(function (totalValues, currentValue) {
        totalValues[currentValue[1].rashi] = totalValues[currentValue[1].rashi] || [];
        totalValues[parseInt(currentValue[1].rashi)].push(currentValue[0]);
        return totalValues;
}, Object.create(null));

will result in following

temp1 = {
  2: ["Gu"],
  5: ["Ke"],
  6: ["Sk"],
  7: ["Sy","Ch","Bu"],
  9: ["Sa"],
  11: ["Ra"],
  12: ["Ma"]
}

In the below line, every item is pushed as value

        totalValues[parseInt(currentValue[1].rashi)].push(currentValue[0]);

We have parsed into an integer for futher computation.

If we add console.log(totalValues), we can observe how totalValues is getting populated.

Convert object to map

map = new Map(Object.entries(temp1))

Check key in a map

if(key in temp1){ // key i in map
   // key is available in map
}  

Array to string

With join method you can convert array into comma separated string

temp1["7"].join(", ")

NodeList forEach

If we wish to add the data on a nodelist, we can iterate over the nodelist using forEach

const houseNodes = document.getElementById('houses').querySelectorAll('p');
houseNodes.forEach(function(houseNode, i){
    houseNode.innerHTML= "House No "+i;    
})

Rotate an array

We can extend Array with a custom function for rotating the array.

Array.prototype.rotate = function(n) {
    n = n % this.length;
    while (this.length && n < 0) n += this.length;
    this.push.apply(this, this.splice(0, n));
    return this;
}

[...map].rotate(5);

Combine Arrays into a single array

Every array has a concat method that can accept another array and produce the combined array. We can reassign this combined array to original array or assign it to a new array.

combined = arr1.concat(arr2)