Categories
JavaScript Answers

How to Build a Tree Array from Flat Array in JavaScript?

Sometimes, we want to build a tree array from a flattened array in JavaScript.

In this article, we’ll look at how to build a tree array from a flattened array with JavaScript.

Use JavaScript Array Methods and Recursion

We can easily build a tree array from a flattened array with various array methods and recursion.

For instance, we can write:

const comments = [{
  id: 1,
  parentId: null
}, {
  id: 2,
  parentId: 1
}, {
  id: 3,
  parentId: 1
}, {
  id: 4,
  parentId: 2
}, {
  id: 5,
  parentId: 4
}];

const nest = (items, id = null, link = 'parentId') =>
  items
  .filter(item => item[link] === id)
  .map(item => ({
    ...item,
    children: nest(items, item.id)
  }));

console.log(nest(comments))

We have the comments array with the id and parentId properties where the parentId the id of the parent comment.

Then we create the nest function that takes the items array, id and link .

id is the value of parentId .

And link has the property name of the parent ID.

In the function, we call filter to get the child comments with the given ID.

Then call map to map the item with the children array property with the child comments that we get from the nest method.

Therefore, the console log should log:

[
  {
    "id": 1,
    "parentId": null,
    "children": [
      {
        "id": 2,
        "parentId": 1,
        "children": [
          {
            "id": 4,
            "parentId": 2,
            "children": [
              {
                "id": 5,
                "parentId": 4,
                "children": []
              }
            ]
          }
        ]
      },
      {
        "id": 3,
        "parentId": 1,
        "children": []
      }
    ]
  }
]

Conclusion

We can unflatten an array and return a tree array with some array methods and recursion with JavaScript.

Categories
JavaScript Answers

How to Append a Property to a JavaScript Object?

Oftentimes, we want to append new properties to a JavaScript object in our code.

In this article, we’ll look at how to append a property to a JavaScript object.

Use the Object.assign Method

One way to append a property to a JavaScript object is to use the Object.assign method.

For instance, we can write:

const obj = {  
  foo: 1,  
  bar: 2  
}  
const newObj = Object.assign({}, obj, {  
  baz: 3  
})  
console.log(newObj)

We have an obj that we want to to add the baz property into it.

To do that, we call Object.assign with an empty object, obj and an object with the baz property.

Then all the properties from the objects in the 2nd and 3rd arguments are put into the empty object and returned.

Therefore, newObj is:

{  
  "foo": 1,  
  "bar": 2,  
  "baz": 3  
}

Use the Spread Operator

Another way to add a property into an object is to use the spread operator.

For instance, we can write:

const obj = {  
  foo: 1,  
  bar: 2  
}  
const newObj = {  
  ...obj,  
  baz: 3  
}  
console.log(newObj)

We spread the properties of obj into newObj .

And then we put the baz property after that.

Therefore, newObj is:

{  
  "foo": 1,  
  "bar": 2,  
  "baz": 3  
}

Conclusion

We can use the Object.assign method or the spread operator to append a property to an object.

Categories
JavaScript Answers

How to Retrieve the Text of the Selected option Element in a select Element with JavaScript?

Sometimes, we want to retrieve the text of the selected option element in a select element with JavaScript.

In this article, we’ll look at how to retrieve the text of the selected option element in a select element with JavaScript.

Use the selectedIndex Property

We can get the index of the selected item with the selectedIndex property.

Then we can use the text property to get the text of the selected item.

For instance, if we have the following HTML:

<select>
  <option value="1">apple</option>
  <option value="2" selected>orange</option>
</select>

Then we can write the following JavaScript code to get the selected item from the select element:

const getSelectedText = (el) => {
  if (el.selectedIndex === -1) {
    return null;
  }
  return el.options[el.selectedIndex].text;
}

const select = document.querySelector('select')
const text = getSelectedText(select);
console.log(text)

We create the getSelectedText function that takes an element as the parameter.

Then we check if selectedIndex is -1.

If it’s -1, then nothing is selected and we return null .

Otherwise, we get the options with el.options .

And then we get the selected option by passing in the el.selectedIndex into the square brackets.

Finally, we get the text property to get the text of the selected option element.

Therefore, the console log should log 'orange' .

Conclusion

We can retrieve the text of a selected option element with the selectedIndex and text properties.

Categories
JavaScript Answers

How to Convert a Unix Timestamp to a Calendar Date with Moment.js and JavaScript?

Sometimes, we want to convert a Unix timestamp to a calendar date with Moment.js and JavaScript.

In this article, we’ll look at how to convert a Unix timestamp to a calendar dare with moment.js and JavaScript.

Use the unix and format Methods

We can use the unix method to create a moment object from a timestamp.

Then we can use the format method to format the date into a calendar date.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment.unix(dt / 1000).format("MM/DD/YYYY");  
console.log(dateString)

We create the dt date object with the Date constructor.

Then we convert it to a timestamp in milliseconds with the unary + operator.

Next, we call moment.unix with a timestamp in seconds.

And then we call format to format the date into MM/DD/YYYY format.

And so dateString is ‘02/01/2021’ .

Use the moment Function and the format Method

We can just use the moment function without the unix method to create a moment object from a timestamp.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment(dt).format("MM/DD/YYYY");  
console.log(dateString)

The moment function takes a timestamp in milliseconds.

Therefore, we don’t have to divide dt by 1000 when we pass it in.

The rest of the code is the same and we get the same result as before.

Conclusion

We can convert a timestamp to a calendar date with format with the moment function or the unix method with the format method.

Categories
JavaScript Answers

How to Get the Browser’s Scrollbar Sizes with JavaScript?

Sometimes, we want to get the scrollbar size of an element with JavaScript.

In this article, we’ll look at how to get the size of the scrollbar that’s part of a scrollable element with JavaScript.

Use the getBoundingClientRect Method and the scrollHeight Property with JavaScript

We can get the element’s scrollbar size with the getBoundingClientRect method and the scrollHeight property of an element with JavaScript.

To do this, we subtract the height property value retuned by getBoundingClientRect method by the scrollHeight property’s value to get the width of the horizontal scrollbar.

For instance, if we have:

<div id="app" style='width: 100px; overflow-x: scroll'></div>

Then we can add elements to the div and get the horizontal scrollbar height by writing:

const app = document.querySelector('#app')
for (let i = 0; i < 100; i++) {
  const span = document.createElement('span')
  span.textContent = i
  app.appendChild(span)
}

const getScrollbarHeight = (el) =>{
  return el.getBoundingClientRect().height - el.scrollHeight;
};
console.log(getScrollbarHeight(app))

We get the div with querySelector .

Then we add some spans into the div.

The div has width set and overflow-x set to scroll.

This means the div should have a horizontal scrollbar.

Next, we create the getScrollbarHeight function that subtracts the height from getBoundingClientRect by the scrollHeight , which gives us the height of the horizontal scrollbar.

Then we log the scrollbar height with console log.

Likewise, we can get the scrollbar width with:

<div id="app" style='height: 100px; overflow-y: scroll'></div>

and:

const app = document.querySelector('#app')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  app.appendChild(p)
}

const getScrollbarHeight = (el) =>{
  return el.getBoundingClientRect().width - el.scrollWidth;
};
console.log(getScrollbarHeight(app))

We add p elements into a div that’s scrollable vertically.

Instead of subtracting the heights, we subtract the widths.

And we should get the scrollbar width from the console log.

Conclusion

We can get the scrollbar width and height by calling the getBoundingClientRect method and the scroll width or height and getting the difference between the 2.