Categories
JavaScript Answers

How to Flatten a Nested JSON Object with JavaScript?

We can loop through each object property and check if a property is an object.

If it is, then we put the key in an object.

For instance, we can write:

const flatten = (obj, prefix = [], current = {}) => {
  if (typeof(obj) === 'object' && obj !== null) {
    for (const key of Object.keys(obj)) {
      flatten(obj[key], prefix.concat(key), current)
    }
  } else {
    current[prefix.join('.')] = obj
  }
  return current
}

console.log(flatten({
  a: [{
    b: ["c", "d"]
  }]
}));
console.log(flatten([1, [2, [3, 4], 5], 6]));

We create the flatten function that takes the obj , prefix , and current parameters.

prefix is the property name of the nested object.

current is the current value of the flattened object.

In the function body, we check if obj is an object and that obj isn’t null .

If they’re both true, then we know obj is an object.

Then we can loop through the keys obtained from Object.keys and call flatten inside the loop with the obj[key] , prefix , and current to traverse to the nested object.

Otherwise, obj isn’t an object and we can put the property as a property of current .

Now when we do run the 2 console log statements, we get:

{a.0.b.0: "c", a.0.b.1: "d"}

and:

{0: 1, 2: 6, 1.0: 2, 1.1.0: 3, 1.1.1: 4, 1.2: 5}

respectively.

Categories
JavaScript Answers

How to Reset the setTimeout Timer with JavaScript?

Sometimes, we want to reset the setTimeout timer so that we can use it again.

In this article, we’ll look at how to reset the setTimeout timer with JavaScript.

Use the clearTimeout Function

We can use the timer created by setTimeout function with the clearTimeout function.

For instance, we can write:

let timer;

const runTimer = () => {
  timer = window.setTimeout(
    () => {
      document.body.style.backgroundColor = 'black'
    }, 3000);
}

runTimer();

document.body.onclick = () => {
  clearTimeout(timer)
  runTimer()
}

We have the timer variable that stores the timer returned by setTimeout .

Then we have the runTimer function that calls the setTimeout function with a callback that turns the page black after 3 seconds.

We assign the returned timer to timer .

Next, we call runTimer to turn the screen black after 3 seconds.

We also have a click handler assigned to the onclick property of document.body to turn the screen black after 3 seconds after clicking it.

The clearTimeout function will reset the timer and will start counting from 0 milliseconds again.

Conclusion

We can reset the timer created by setTimeout function with the clearTimeout function.

Categories
JavaScript Answers

How to Replace Text Inside a div Element with JavaScript?

Sometimes, we want to replace text inside a div element with JavaScript.

In this article, we’ll look at ways to replace text inside a div element with JavaScript.

Set the innerHTML Property of an Element

One way to replace the text inside a div element with JavaScript is to set the innerHTML property of an element to a different value.

If we have the following HTML:

<div>  
  hello world  
</div>

Then we can write:

const div = document.querySelector('div')  
div.innerHTML = "My new text!";

to select the div with querySelector .

And then we can set the innerHTML to a new string.

Set the textContent Property of an Element

Another way to replace the text inside a div element with JavaScript is to set the textContent property of an element to a different value.

If we have the following HTML:

<div>  
  hello world  
</div>

Then we can write:

const div = document.querySelector('div')  
div.textContent = "My new text!";

to select the div with querySelector .

And then we can set the textContent to a new string.

Then we get the same result as before.

Set the innerHTML Property of an Element to an Empty String and Insert a new Child Text Node to the Element

Another way to replace the text in a div is to set the innerHTML property to an empty string.

Then we can add a new text node and insert it into the div.

If we have the following HTML:

<div>  
  hello world  
</div>

Then we can write:

const div = document.querySelector('div')  
div.innerHTML = '';  
div.appendChild(document.createTextNode("My new text!"));

to set innerHTML to an empty string.

Then we call document.createTextNode to create a new text node with the text in the argument.

And then we call appendChild to insert the text node to the div.

Conclusion

There are various ways we can use to replace text in a div element with new text in JavaScript.

Categories
JavaScript Answers

How to Create a String of Variable Length Filled with a Repeated Character with JavaScript?

Sometimes, we want to create a string of variable length filled with a repeated character in JavaScript.

In this article, we’ll look at ways to create such strings with JavaScript.

Using the Array Constructor and the Arra.prototype.join Method

We can create an array with the Array constructor.

Then we can call join to join the array entries into a string with the given character as the separator.

For instance, we can write:

const len = 10  
const character = 'a'  
const str = new Array(len + 1).join(character);  
console.log(str)

We create an Array with length len + 1 .

Then we call join with the character that we want to repeat.

Therefore, str is 'aaaaaaaaaa’ .

Use the String.prototype.repeat Method

Another way to create a string of variable length with a repeated character is to use the string’s repeat method.

For instance, we can write:

const len = 10  
const character = 'a'  
const str = character.repeat(len);  
console.log(str)

Then we get the same result as before.

Use a for Loop

We can also use a for loop to concatenate the same character to a string until it reaches the given length.

To do this, we write:

const len = 10  
const character = 'a'  
let str = ''  
for (let i = 1; i <= len; i++) {  
  str += character;  
}  
console.log(str)

We have a for loop that starts with index variable 1 and stops when it reaches len .

In the loop body, we concatenate the character to str .

And so we get the same result as before.

Conclusion

We can create a string that has a variable length with content consisting of a repeated character by using array methods, string methods, or loops.

Categories
JavaScript Answers

How to Get the First Day of the Week from the Current Date with JavaScript?

Sometimes, we want to get the first day of the week from the current date with JavaScript.

In this article, we’ll look at how to get the first date of the week from the current date with JavaScript.

Using Native Date Methods

We can use various date methods to get the first day of the week from the current date.

To do this, we can write:

const getMonday = (d) => {
  const dt = new Date(d);
  const day = dt.getDay()
  const diff = dt.getDate() - day + (day === 0 ? -6 : 1);
  return new Date(dt.setDate(diff));
}

console.log(getMonday(new Date(2021, 1, 20)));

We create the getMonday function takes the d date parameter.

In the function, create a Date instance with the Date constructor.

Then we call getDay to get the day of the week.

It returns 0 for Sunday, 1 for Monday, and so on up to 6 for Saturday.

Then we get the difference between the current date of the week and the Monday of the same week by subtracting the day and then add -6 back if day is 0 and 1 otherwise.

And then we use the Date constructor again by call setDate on dt with diff to set the day to the Monday of the same week.

Therefore, the console log should log:

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

as a result.

Conclusion

We can get the Monday of the same week of the given date by getting the day of the week.

Then we subtract the date by the day of the week then add back the number of days to reach the Monday of the same week of the date.