Categories
JavaScript Answers

How to Remove Objects from a JavaScript Array by Object Property?

Sometimes, we want to remove an object from a JavaScript array that has the given property value.

In this article, we’ll look at how to remove objects from a JavaScript array given a property value.

Using the Array.prototype.splice and Array.prototype.findIndex Methods

We can use the JavaScript array findIndex method to find the index of the object in an array with the given property value.

Then we can use the JavaScript array splice method to remove the item with the index returned by findIndex .

For instance, we can write:

const items = [{
    id: 'abc',
    name: 'oh'
  },
  {
    id: 'efg',
    name: 'em'
  },
  {
    id: 'hij',
    name: 'ge'
  }
];
const index = items.findIndex((i) => {
  return i.id === "abc";
})
items.splice(index, 1);
console.log(items)

We have the items array with a bunch of objects.

And we want to remove the one with id set to 'abc' .

To do that, we call items.findIndex with a callback that returns id.id === 'abc' so we can get the index of the object with the id set to 'abc' .

Then we can call items.splice with the index and 1 to remove the item at the given index from items .

Therefore, items is now:

[
  {
    "id": "efg",
    "name": "em"
  },
  {
    "id": "hij",
    "name": "ge"
  }
]

Conclusion

We can use the findIndex method to find the index of an object in an array that meets the given condition.

Then we can use the splice method to remove the item at the index returned by findIndex to remove the item from the array.

Categories
JavaScript Answers

How to Convert a JSON String to a JavaScript Object with JavaScript?

Sometimes, we want to convert a JSON string into a JavaScript object.

In this article, we’ll look at how to convert a JSON string to a JavaScript object.

Use the JSON.parse Method

We can use the JSON.parse method to convert a JSON string into a JavaScript object.

For instance, we can write:

const string = `
  {
    "foo": 1,
    "bar": 2
  }
`
const obj = JSON.parse(string);
console.log(obj)

We have a string with a JSON object as its content.

Then we pass string into JSON.parse to parse it into an object and assign it to obj .

Therefore, obj is:

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

as we expect.

JSON.parse is available in all modern browsers so we can use it anywhere.

Conclusion

We can use the JSON.parse method to parse a JSON object string into a JavaScript object.

Categories
JavaScript Answers

How to Create a File Object in JavaScript?

Sometimes, we want to create a file object without our JavaScript code.

In this article, we’ll look at how to create a file object with JavaScript.

Create a File Object with the File Constructor

We can create a file with the File constructor with JavaScript.

For instance, we can write:

const parts = [
  new Blob(['you construct a file...'], {
    type: 'text/plain'
  }),
  ' Same way as you do with blob',
  new Uint16Array([33])
];

const file = new File(parts, 'sample.txt', {
  lastModified: new Date(2020, 1, 1),
  type: "text/plain"
});

const fr = new FileReader();

fr.onload = (evt) => {
  document.body.innerHTML = `
   <a href="${URL.createObjectURL(file)}" download="${file.name}">download</a>
    <p>file type: ${file.type}</p>
    <p>file last modified: ${new Date(file.lastModified)}</p>
  `
}

fr.readAsText(file);

We create the parts array with the parts of a file.

The first entry of parts is a Blob instance with the file content.

The first argument of Blob is the file content in an array.

The 2nd argument of Blob has the file metadata.

The 2nd and 3rd entries of parts has more file content.

Next, we use the File constructor to create a file object.

The first argument is the file content, which we stored in parts .

The 2nd argument is the file name.

The 3rd argument is some metadata.

Next, we create a FileReader instance so we can read the file contents.

We set the onload property of it to watch when the file loads into memory.

In the callback, we get the file metadata from the file .

And we use URL.createObjectURL with file to create a URL so we can download the file from a link we create by setting it as the value of href .

When we call readAsText with file , the onload method will run.

Now when we click on download, we see the sample.txt file download with the content that we put into parts in the text file.

Conclusion

We can create a file with the File constructor. And then we can read the file with the FileReader object.

Categories
JavaScript Answers

How to Check if a JavaScript Object Property is a Method?

In JavaScript, a method is a JavaScript object property that has a function as its value.

Sometimes, we want to check if an object property is a method.

In this article, we’ll look at how to check if a JavaScript object property is a method.

Use the typeof Operator

We can use the typeof operator to check if an object property is a method.

If an object property is a method, then the typeof operator should return 'function' .

For instance, we can write:

const obj = {
  prop1: 'no',
  prop2() {
    return false;
  }
}

console.log(typeof obj.prop2 === 'function');

to check if obj.prop2 is a method.

If it’s a method, then typeof obj.prop2 should return 'function' .

The console log logs true , so we know obj.prop2 is a method.

If it’s not a method or it doesn’t exist, then typeof obj.prop2 won’t return 'function' .

Conclusion

We can use the typeof operator to check if an object property is a method.

Categories
JavaScript Answers

How to Remove the Query String from URL with JavaScript?

Sometimes, we want to remove the query string part of a URL with JavaScript.

In this article, we’ll look at how to remove the query string part of a URL string with JavaScript.

Use the String.prototype.split Method

We can use the JavaScript string split method to remove the query string from the URL string.

For instance, we can write:

const getPathFromUrl = (url) => {
  return url.split("?")[0];
}
const testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
console.log(getPathFromUrl(testURL))

to create the getPathFromUrl function that returns the part of the URL before the query string.

The query string always follows the question mark, so we can use split with any URL.

We call split on the url with '?' as the separator with [0] to get the part before the query string.

Therefore, in the console log, we see '/Products/List’ is logged.

Use the String.prototype.replace Method

Another way to remove the query string from the URL is to use the JavaScript string replace method.

For instance, we can write:

const getPathFromUrl = (url) => {
  return url.replace(/(?.*)|(#.*)/g, "")
}
const testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
console.log(getPathFromUrl(testURL))

We call replace with a regex to remove the part of the URL after the ? and also the part after the # sign with an empty string.

And so, we get the same result as we did in the previous example.

Conclusion

We can remove the query string part of a URL string in JavaScript with some string methods.