Categories
JavaScript Answers

How to Convert a JavaScript Object to an Array?

To convert a JavaScript object to an array, we can use the Object.entries method to get the key-value pairs from the object into an array.

Then we can use the JavaScript array’s map method to return each entry in an array.

For instance, we can write:

const input = {
  "fruit": ["mango", "orange"],
  "veg": ["carrot"]
};

const output = Object.entries(input).map(([key, val]) => {
  return {
    type: key,
    name: val
  };
});

console.log(output)

We have the input object that has several properties.

Then we call Object.entries with input to return an array of key-value pair arrays.

Next, we call map with a callback that destructures the key-value pair from the parameter and return an object with the key and val set as values of the object.

Therefore, output is:

[
  {
    "type": "fruit",
    "name": [
      "mango",
      "orange"
    ]
  },
  {
    "type": "veg",
    "name": [
      "carrot"
    ]
  }
]
Categories
JavaScript Answers

How to Convert inline SVG to Base64 string with JavaScript?

To convert inline SVG to base64 string with JavaScript, we can use the serializeToString method available with a XMLSerializer instance to parse the svg element to an XML string.

Then we call window.btoa to convert the string into a base64 string.

For instance, if we have:

<svg height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

Then we write:

const s = new XMLSerializer().serializeToString(document.querySelector("svg"))
const encodedData = window.btoa(s);
console.log(encodedData)

We call serializeToString with the svg element object that’s returned with document.querySelector.

Then we call window.btoa on the string returned by serializeToString.

Therefore, from the console log, we get:

PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTAwIiB3aWR0aD0iMTAwIj4KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgc3Ryb2tlPSJibGFjayIgc3Ryb2tlLXdpZHRoPSIzIiBmaWxsPSJyZWQiLz4KPC9zdmc+

logged as a result.

Categories
JavaScript Answers

How to Round to Nearest Hour Using JavaScript Date Object?

To round to nearest hour using JavaScript Date Object, we can call setHours to round the hour of the date to the nearest hour.

And we call setMinutes to set the minutes, seconds, and milliseconds of a date all to 0.

For instance, we can write:

const roundMinutes = (date) => {
  date.setHours(date.getHours() + Math.round(date.getMinutes() / 60));
  date.setMinutes(0, 0, 0);
  return date;
}

const date = new Date(2021, 1, 1, 4, 55);
const newDate = roundMinutes(date);
console.log(newDate)

We create the roundMinutes which takes a date object.

In the function, we call date.setHours with date.getHours() + Math.round(date.getMinutes() / 60).

We get the hour of the date with getHours. Then we add Math.round(date.getMinutes() / 60) to add one hour if date.getMinutes() / 60 is 0.5 or bigger.

Then we call setMinutes with 3 zeroes to set the minutes, seconds, and milliseconds all to 0 respectively.

Therefore, when we call roundMinutes with date, we get:

Mon Feb 01 2021 05:00:00 GMT-0800 (Pacific Standard Time)

from the console log.

Categories
JavaScript Answers

How to Limit the Amount of Number Shown After a Decimal Place in JavaScript?

To limit the amount of number shown after a decimal place in JavaScript, we can use the toFixed method.

For instance, we can write:

const x = 4.8855;
console.log(x.toFixed(2));

Then we round x to 2 decimal places.

The number of decimal places is the argument for toFixed.

Therefore, the console log should log 4.89.

Categories
JavaScript Answers

How to Parse JSON Arrays and Display the Data in an HTML Table with JavaScript?

To parse JSON arrays and display the data in an HTML table with JavaScript, we can loop through each entry of the array, create tr elements for each, and insert them into the table element.

For instance, we write:

<table>

</table>

to create the table element.

Then we write:

const data = [{
  "User_Name": "John Doe",
  "score": "10",
  "team": "1"
}, {
  "User_Name": "Jane Smith",
  "score": "15",
  "team": "2"
}, {
  "User_Name": "Chuck Berry",
  "score": "12",
  "team": "2"
}]

let tr;
for (const d of data) {
  tr = $('<tr/>');
  tr.append(`<td>${d.User_Name}</td>`);
  tr.append(`<td>${d.score}</td>`);
  tr.append(`<td>${d.team}</td>`);
  $('table').append(tr);
}

to put the content of data into a table.

We loop through data with a for-of loop.

Then in the loop body, we create a tr element with $('<tr/>').

Then we append the td elements for each column with:

tr.append(`<td>${d.User_Name}</td>`);
tr.append(`<td>${d.score}</td>`);
tr.append(`<td>${d.team}</td>`);

Then we append the tr element with the content to the table element with:

$('table').append(tr);