Categories
JavaScript Answers

How to Get the Length of a JavaScript Object?

Getting the length of a JavaScript object means getting the number of properties in an object.

This is something we might do sometimes.

In this article, we’ll look at how to get the length of a JavaScript object.

Object.keys

The Object.keys lets us get the non-inherited string keys of an object as an array.

This means we can use the length property of the returned array to get the length of an object.

This method has been available since ES6, so we can use it safely anywhere.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
}
const size = Object.keys(obj).length;
console.log(size)

We call Object.keys with the obj object to get an array of non-inherited string keys from obj .

It doesn’t include non-enumerable properties, which are properties that we can’t loop through with the for-in loop.

Object.getOwnPropertyNames()

We can use the Object.getOwnPropertyNames() method to get all non-inherited string keys of an object, including non-inherited properties.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
}
const size = Object.getOwnPropertyNames(obj).length;
console.log(size)

There’s no difference between the previous example and this one since all the properties of obj are enumerable.

However, if there’re any non-enumerable properties set for an array, then we’ll get different results because of the extra non-enumerable properties returned with Object.getOwnPropertyNames .

Symbol Keys

The 2 methods above don’t return any symbol keys.

To return symbol keys, we’ve to use the Object.getOwnPropertySymbols method.

For instance, if we have an object with symbol keys, then we can call this method by writing:

const obj = {
  [Symbol('a')]: 1,
  [Symbol('b')]: 2
}
const size = Object.getOwnPropertySymbols(obj).length;
console.log(size)

We get the size is 2 since there’re 2 symbol keys in the object.

If an object has both symbol and string keys, then we can use Object.keys or Object.getOwnPropertyNames with Object.getOwnPropertySymbols .

For instance, we can write:

const obj = {
  [Symbol('a')]: 1,
  [Symbol('b')]: 2,
  c: 3
}
const symbolSize = Object.getOwnPropertySymbols(obj).length;
const stringSize = Object.getOwnPropertyNames(obj).length;
const size = symbolSize + stringSize
console.log(size)

We add symbolSize and stringSize together to get the total number of keys in obj .

So size is 3.

Conclusion

To get the number of string keys in an object, we can use Object.getOwnPropertyNames or Object.keys .

And to get the number of symbol keys of an object, we can use Object.getOwnPropertySymbols .

Categories
JavaScript Answers

How to Format a Number with Commas as Thousands Digit Separators in JavaScript?

Formatting a number with commas as thousands digit separators is something we do to make numbers easy to read.

In this article, we’ll take a look at how to format numbers with commas as thousands digit separators in JavaScript.

Replace with Regex

We can use the replace method with a regex to add a comma every 3 digits.

To do this, we write:

const str = (1234567890).toString().replace(/B(?=(d{3})+(?!d))/g, ",");
console.log(str)

The B(?=(d{3})+ looks for groups of 3 digits before the decimal place.

The B keeps replace from adding a comma at the beginning of the string.

?= is a lookahead assertion.

It means we only match 3 digits if the 3 digit pattern is followed by a non-word boundary.

?! is a negative lookahead assertion.

It means we match the one-digit pattern only if it’s preceded by the 3 digit pattern.

So we make sure that we insert commas only if 3 digits are followed by another digit.

So we get ‘1,234,567,890’ as the value of str

The toLocaleString Method

The toLocaleString method lets us format a number to a string with commas as thousands separators automatically.

For instance, we can write:

const str = (1234567890).toLocaleString()
console.log(str)

We call toLocaleString directly on the number that we want to format.

So we get ‘1,234,567,890’ as the value of str

We can also set the locale to guarantee that the formatted value will always have the commas:

const str = (1234567890).toLocaleString('en-US')
console.log(str)

NumberFormat Constructor

We can also use the format method of a NumberFormat instance.

To use it, we write:

const nf = new Intl.NumberFormat();
const str = nf.format(1234567890);
console.log(str)

We create a Intl.NumberFormat instance.

Then we call format on the instance with a number.

Then we get the same result as the other examples.

Conclusion

We can add commas as thousands separators with a regex replace, or we can use formatter functions to do the same thing.

Categories
JavaScript Answers

How to do Object Comparison in JavaScript?

Comparing object properties and values is something that we need to do sometimes in our JavaScript code.

In this article, we’ll look at how to compare objects in JavaScript.

JSON.stringify

The JSON.stringify method lets us convert a JavaScript object into a JSON string.

Once we converted our object into a string, we can compare the stringified value against another object that’s stringified.

For instance, we can write:

const obj1 = {
  a: 1
}
const obj2 = {
  a: 1
}
console.log(JSON.stringify(obj1) === JSON.stringify(obj2))

We have 2 objects, obj1 and obj2 .

Then we call JSON.stringify on both objects and check for equality with the === operator.

The order of the properties matter since they’re going to stringified in the same order that they are in the object.

Since obj1 and obj2 are the same stringified, then the boolean expression in the last line should be true .

Comparing Each Property of an Object

We can compare each property of the objects that we want to compare.

For instance, we can write:

const obj1 = {
  a: 1
}
const obj2 = {
  a: 1
}

function objectEquals(x, y) {
  if (x === y) {
    return true;
  }

  if (!(x instanceof Object) || !(y instanceof Object)) {
    return false;
  }

  if (x.constructor !== y.constructor) {
    return false;
  }

  for (const p in x) {
    if (!x.hasOwnProperty(p)) {
      continue;
    }

    if (!y.hasOwnProperty(p)) {
      return false;
    }

    if (x[p] === y[p]) {
      continue;
    }

    if (typeof(x[p]) !== "object") {
      return false;
    }

    if (!objectEquals(x[p], y[p])) {
      return false;
    }
  }

  for (const p in y) {
    if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
      return false;
    }
  }
  return true;
}

console.log(objectEquals(obj1, obj2))

In the objectEquals function, we check if x and y are equal with the === operator.

If they’re equal, then we return true .

The next if block checks if either of them isn’t an object literal with the instanceof operator.

If either of them aren’t, then we return false since it’s impossible for them to be the same if either of them isn’t an object.

Next, we loop through the properties of x .

If a property p isn’t an own property of x , then we ignore it with continue .

If y doesn’t have an inherited property that is in x , then they aren’t the same, so we return false .

If x[p] and y[p] are the same, then use continue to check the new property.

If x[p] isn’t an object, we return false since it’s impossible for x and y to be equal if a primitive value isn’t equal.

Then we also have to remember to check the remaining levels of x and y for equality with objectEquals(x[p], y[p]) .

If any of them aren’t equal, then we return false .

Next, we loop through y and check if there are any non-inherited properties in y that isn’t in x .

If there is, then we know they aren’t equal and we return false .

If all the checks pass, then we return true since we know they’re definitely equal in this case.

Conclusion

We can write our own code to compare complex objects, or we can use JSON.stringify to compare 2 objects as JSON strings.

Categories
JavaScript Answers

How to Remove a Specific Item from a JavaScript Array?

Removing an item from a JavaScript array is something that we have to do often.

In this article, we’ll look at how to remove a specific item from a JavaScript array.

The indexOf and splice Methods

One way to remove an item from an array is to use the indexOf method to get the index of the item we want to remove.

Then we can use the splice method to remove an item with the given index.

For instance, we can write:

const array = [1, 2, 3];

console.log(array);

const index = array.indexOf(2);
if (index > -1) {
  array.splice(index, 1);
}

We have the array array.

Then we call indexOf to get the index of 2 in array .

And then we call splice with index and 1 to remove 1 item starting with index index .

This means we remove the item with index index in array with splice if index is bigger than -1.

indexOf returns -1 if the item doesn’t exist in array .

The filter Method

We can call filter to return an array without the item we want to remove.

For instance, we can write:

let array = [1, 2, 3];
const value = 3
array = array.filter((item) => {
  return item !== value
})

We have the array which is the array, and value which is the value want to remove from array .

Then we call filter with a callback to return item !== value .

This means that we want the array returned by item to not include the item with the value value .

Therefore, array should be [1, 2] .

Removing Multiple Items

If we want to remove multiple items, we can also use the filter method, but with a different callback.

To remove multiple items, we can write:

let array = [1, 2, 3];
const forDeletion = [2, 3]
const value = 3
array = array.filter((item) => {
  return !forDeletion.includes(item)
})
console.log(array)

We call array.filter with a callback that checks if the item isn’t in the forDeletion array.

forDeletion is an array with the items we want to delete.

So if it’s not included in forDeletion , then we want to keep them.

Since 2 and 3 in in forDeletion , that means only 1 is kept in the returned array.

Conclusion

The array instances’ includes , indexOf , splice , and filter methods are handy for removing items in an array.

Categories
JavaScript Answers

How to Change an Element’s Class with JavaScript?

If we’re working with web front end apps, then changing an element’s class is something that we’ve to do often.

In this article, we’ll take a look at how to change an element’s class with JavaScript.

The classList Property

An element has the classList property to let us manipulate the classes that are applied to the element.

For instance, if we have a div:

<div>
  hello world
</div>

Then to add a class to the div, we can write:

document.querySelector("div").classList.add('hello');

We call add to add the 'hello' class to the div.

If the hello class is already added, then nothing will be done.

To remove a class, we can call the classList.remove method:

document.querySelector("div").classList.remove('hello');

To check if a class is already present in an element, we can use the classList.contains method:

document.querySelector("div").classList.contains('hello');

It returns true if the class is applied to the div and false otherwise.

And to toggle class that’s applied to an element, we can call the classList.toggle method:

document.querySelector("div").classList.toggle('hello');

If the hello class is applied to the div, then it’ll be removed.

Otherwise, the hello class will be added to the div.

This is available in most recent browsers.

The className Property

Another way to manipulate classes of an element is to manipulate the className string property.

For instance, we can write:

document.querySelector("div").className = 'hello';

We get the div and set the className to 'hello' to set the class attribute of the div to 'hello' .

To add a class by manipulating the className property, we can write:

document.querySelector("div").className += ' hello';

We add a space and hello to add the hello class to the div.

To remove the hello class, we can use the replace method:

document.querySelector("div").className.replace(/(?:^|s)hello(?!S)/g, '')

We check for hello with possible spaces at the start or end of the class name and replace them with an empty string.

The g flag will find all the instances of this and do the replacement on all of them.

To find if a class is in the div, we can write:

document.querySelector("div").className.match(/(?:^|s)hello(?!S)/)

We call match with the regex that matches hello with whitespace before or after it to check if the class is in the className string.

Conclusion

The best and easiest way to manipulate classes of an HTML element is to use the classList property.

Alternatively, we can also manipulate the className string property to change the class attribute of an element.