Categories
JavaScript Answers

How to Extract a Value of a Property as an Array From an Array of JavaScript Objects?

Extracting a property value from an array of JavaScript objects is something that we’ve to do often.

In this article, we’ll look at how to create an array from property values extracted from an array of JavaScript objects.

The Array map Method

The map method is available in a JavaScript array instance that lets us map one array to another.

This means we can use it to extract property from each object in the array and put the extracted values in its own array.

For instance, we can write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = objArray.map(a => a.foo);

We have the objArray array with objects with the foo property.

Then we call map with a function to return the value of the foo property from each array element.

a is the array element being iterated through.

Therefore, result is [1, 2, 3] .

We can also write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = objArray.map(({
  foo
}) => foo)

In the map callback, we destructure the a object with the parameter.

So we can just get foo and return it.

Lodash

We can also use Lodash methods to do the same thing.

We can use the pluck method to map an array of objects to an object with the property value of a given property from each object in the array.

For instance, we can write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = _.pluck(objArray, 'foo');

In the last line, we pass in objArray , which is the object array.

And the second has the argument of the property we want to get from each object in the array.

Therefore, result should give us the same answer as in the previous examples.

Lodash also has a map method to let us do the same thing.

For instance, we write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = _.map(objArray, 'foo');

The arguments are the same as the ones taken by pluck and it returns the same result.

The latest version of Lodash also comes with the property method which we can combine with the map method by writing:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = _.map(objArray, _.property('foo'));

property returns an accessor a given property name we pass into the method.

And the accessor is recognized by map and it’ll use the accessor to extract the property from each object in the array.

Therefore, we get the same result as the other examples.

Conclusion

We can use plain JavaScript or Lodash to extract the value of a property from each object in an array.

Categories
JavaScript Answers

How to Check if an Object is Empty in JavaScript?

Checking for an empty object is something that we might have to do sometimes.

In this article, we’ll look at various ways we can check if an object is empty with JavaScript.

Object.keys and the constructor Property

We can combine the Object.keys method and the constructor property to check if an object is an empty object.

To do this, we write:

const obj = {}
console.log(obj &&
  Object.keys(obj).length === 0 && obj.constructor === Object)

obj makes sure that obj isn’t null or undefined .

Object.keys(obj).length === 0 checks that the number of keys in obj is 0.

Object.keys returns array of non-inherited keys of an object.

However, we don’t have any check to see if obj is an object literal.

And so, we need to write:

obj.constructor === Object

to check that.

If it’s an object literal, then it should be created from the Object constructor.

So obj.constructor should return Object is obj is an object literal.

This only one way to check for an empty object.

There are few other ways to do this.

JSON.stringify

We can check for an object with the JSON.stringify method.

For instance, we can write:

function isEmpty(obj) {
  for (const prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      return false;
    }
  }

  return JSON.stringify(obj) === JSON.stringify({});
}

We loop through the ketys with the for-in loop.

Then we check if an object has any non-inherited properties with hasOwnProperties .

If obj.hasOwnProperties returns true with any prop value, which has the key that’s being iterated through, then we should return false .

This is because this means a non-inherited key exists in obj and obj isn’t empty.

If the loop finds no keys, then we can use JSON.stringify to check for an stringified empty object.

This is good for supporting runtime environments that don’t have the Object.keys method, which should be rare.

Lodash isEmpty Method

The isEmpty method comes with Lodash and it lets us check if an object is empty.

We just pass in an object we want to check:

_.isEmpty({});

Object.getOwnPropertyNames

The Object.getOwnPropertyNames method returns an array of non-inherited keys of an object.

So we can use it like Object.keys to check for an empty object.

For instance, we can write:

if (Object.getOwnPropertyNames(obj).length === 0) {
  //...
}

We just check if the returned array has 0 length.

It also returns non-enumerable properties, which means it returns keys that won’t be returned by Object.keys , but aren’t inherited from any prototype object.

Therefore, this check is more comprehensive than checking with Object.keys .

Conclusion

There are several ways to check for an empty object with JavaScript.

The best ways are to use Object.keys or Object.getOwnPropertyNames .

Categories
JavaScript Answers

How to Copy Text to a Clipboard Programmatically in JavaScript?

Copying text to the system clipboard programmatically is something that we may have to do sometimes.

We can do this with plain JavaScript code in web apps.

In this article, we’ll look at how to copy text to a clipboard in JavaScript programmatically.

The Old Way

The old way is to create a text area, put the text we want to copy to it, then call document.execCommand to run the copy command to copy the text to the clipboard.

For instance, we can write:

const text = 'hello world'
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";

document.body.appendChild(textArea);
textArea.focus();
textArea.select();

try {
  const successful = document.execCommand('copy');
  const msg = successful ? 'successful' : 'unsuccessful';
  console.log(msg);
} catch (err) {
  console.error(err);
}

document.body.removeChild(textArea);

The text variable has the text that we want to copy to the clipboard.

We then create the document.createElement method to create a textarea element.

Then we set the textArea ‘s value to text to put the text in the text area.

Next, we set the top , left and position styles to prevent scrolling to the bottom.

Then we call document.body.appendChild with textArea to add the text area to the body.

Next, we focus on the textArea with focus .

Then we call select to select the text in the text area so we can copy it.

Next, we call document.execCommand with 'copy' to issue the copy command to copy the text we selected in the text area.

It returns a boolean to indicate whether the command was successfully run.

Then we can paste the text anywhere we want.

The New Way

The new way of copying text programmatically to the clipboard with JavaScript is a lot cleaner.

We just call the navigator.clipboard.writeText method with the text we want to copy as the argument to copy the text programmatically to the clipboard.

To do it, we write:

const text = "abc";
(async () => {
  await navigator.clipboard.writeText(text);
})();

We just call navigator.clipboard.writeText with text to copy the text.

It returns a promise with the copy status so we can put it in an async function.

This is supported in newer browsers.

Conclusion

There are various ways to copy data to the clipboard programmatically with JavaScript.

Categories
JavaScript Answers

How to Check if an Array Includes a Value in JavaScript?

Checking if an array includes a value is something that we’ve to do often in a JavaScript app.

In this article, we’ll look at how to check if an array includes a given value in JavaScript.

Array.prototype.includes

The includes method is a method that’s included with the array instance.

It takes a value and compares it with === to check if an element is included.

For instance, we can write:

console.log(['apple', 'orange', 'grape'].includes('orange'));

If it’s included, then it returns true .

Otherwise, it returns false .

Array.prototype.indexOf

We can also use the indexOf method of an array instance to check if it includes a given element.

It also uses === for comparison.

And it returns the index of the first instance of an item if it exists.

Otherwise, it returns -1.

To use it, we write:

console.log(['apple', 'orange', 'grape'].indexOf('orange') >= 0);

Write Our Own

We can write our own function to search for a value.

For instance, we can write:

function contains(a, obj) {
  let i = a.length;
  while (i--) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
}

console.log(contains(['apple', 'orange', 'grape'] , 'orange'));

We create the contains function that uses a while loop to search for an item.

If a[i] has the same value as obj then we return true .

If we loop through the whole a array and didn’t find anything that matches, then we return false .

Array.prototype.some

The some method is another array instance method that comes with JavaScript arrays.

It lets us pass in a callback to check if any items match the given condition.

For instance, we can write:

const items = [{
  a: '1'
}, {
  a: '2'
}, {
  a: '3'
}]

console.log(items.some(item => item.a === '3'))

We have an items array that has a bunch of objects.

And we call items.some with a callback to check if any items entry with a property equal to 3 exists.

some returns true if an item that matches the given condition exists and false otherwise.

Conclusion

There’re many ways to find if an array item exists in JavaScript.

Categories
JavaScript Answers

How to Get a Timestamp in JavaScript?

A UNIX timestamp is the number of seconds since January 1, 1970 midnight UTC.

It’s often used so that we can do calculations with time easily.

In this article, we’ll look at how to get the UNIX timestamp from a date object in JavaScript.

The + Operator

We can use the + operator to convert the date object right to a UNIX timestamp.

For instance, we can write:

+new Date()

The + operator before the date object triggers the valueOf method in the Date object to return the timestamp as a number.

The getTime Method

We can call getTime to do the same thing.

For instance, we can write:

new Date().getTime()

to return the UNIX timestamp of a date.

Date.now Method

Date.now is a static method of the Date constructor that lets us get the current date-times timestamp.

For instance, we can write:

Date.now()

The timestamp is returned in milliseconds, so we have to divide it by 1000 and round it to get the timestamp in seconds.

To do that, we write:

Math.floor(Date.now() / 1000)

Math.floor rounds the number down to the nearest integer.

We can also round it with Math.round by writing:

Math.round(new Date().getTime() / 1000);

Number Function

The Number function is a global function that lets us convert a non-number object or primitive value to a number.

And we can use it to convert a date to a timestamp.

To do that, we write:

Number(new Date())

Then we get the timestamp in seconds returned since it triggers the valueOf method of the Date instance like the + operator.

Lodash _.now Method

Lodash also has a now method that returns the current timestamp.

To use it, we write:

_.now();

It’ll also return the current date’s timestamp.

Conclusion

There’re many ways to get the timestamp of the current date and time or the date-time that we want with JavaScript.