Categories
JavaScript Answers

How to Find an Object by ID in an Array of JavaScript Objects?

Finding an object by ID or another property in an array of JavaScript objects is something that we’ve to do a lot in our JavaScript code.

In this article, we’ll look at how to find an object by ID in an array of JavaScript objects in our code.

Array.prototype.find

JavaScript arrays come with the find method to let us find an object in an array with the condition we specify in the callback and return the first instance of the object that meets the condition.

If the object with the given condition isn’t found, then it returns undefined .

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const obj = arr.find(x => x.id === 2)
console.log(obj)

arr is an array of objects with the id and foo properties.

Then we call the find method with a callback that returns the condition with the object we’re looking for.

The x parameter is the object that’s being iterated through to find the object.

Therefore, obj is:

{id: 2, foo: "bar"}

Array.prototype.findIndex

The findIndex method lets us find the item that matches the given condition, but it returns the index of the first instance of the element that meets the condition instead of returning the whole object.

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const index = arr.findIndex(x => x.id === 2)
console.log(index)

Then index is 1 since the callback specifies that we find the first object with the id property set to 2.

{id: 2, foo: "bar"}

Array.prototype.filter

The filter method also lets us find array entries that meet the given condition.

It returns an array with all the elements that meet th given condition.

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const results = arr.filter(x => x.id === 2)

The callback is the same as the other examples as it returns the condition of the items we want to find.

Then we get:

[
  {
    "id": 2,
    "foo": "bar"
  }
]

If we only want to get one element from the array, we can get it by index by writing:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const results = arr.filter(x => x.id === 2)
console.log(results[0])

Then we get:

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

Also, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const [result] = arr.filter(x => x.id === 2)

to destructure the first result from the returned array.

Conclusion

We can use native JavaScript array methods to find an object by ID in our code.

Categories
JavaScript Answers

How to Check if a JavaScript String Starts With Another String?

Sometimes we have to check whether a JavaScript string starts with a given substring.

In this article, we’ll look at how to check if a JavaScript string starts with another string.

String.prototype.startsWith

ES6 added the startsWith method to a string.

For instance, we can write:

console.log("hello world".startsWith("hello"));

We call startsWith on the string and we pass in the substring that we want to check whether the 'hello world' string starts with it.

The console log should show true since 'hello world' starts with 'hello' .

String.prototype.substring

Another way to check if a string starts with the given substring is to use the substring method.

It takes the start and end index as the argument.

And it returns the substring beginning with the starting index to the end index minus 1.

Therefore, we can write:

const data = 'hello world'  
const input = 'hello'  
console.log(data.substring(0, input.length) === input)

data is the full string.

substring has arguments 0 and input.length to extract the substring from index 0 to input.length  —  1 .

So subtring should return 'hello' , which is the same as input .

Regex Test

We can search for a given pattern with JavaScript regex object’s test method.

And we can check whether a string begins with a given substring by using the ^ symbol to start searching for a pattern at the beginning of a string.

For instance, we can write:

console.log(/^hello/.test('hello world'))

to check whether 'hello world' starts with hello .

Equivalently, we can use the RegExp constructor to create the regex object:

console.log(new RegExp('^hello').test('hello world'))

This lets us pass in a regex string to create the regex object instead of creating a regex literal.

So it’s handy for creating regex objects dynamically.

String.prototype.lastIndexOf

A JavaScript string also comes with the lastIndexOf method to check the last index of a given substring in a string.

To use it to check whether a string starts with a given substring, we can write:

console.log('hello world'.lastIndexOf('hello', 0) === 0)

We call lastIndexOf with the substring we’re searching for like the first argument.

The 2nd argument is the index that we start searching for the substring from.

If it returns 0, then we know the substring is located in index 0 and starts there.

String.prototype.indexOf

We can replace lastIndexOf with indexOf to get the same behavior.

Instead of searching for the last instance of a substring with lastIndexOf .

We can search for the search instance of a substring with indexOf .

It makes no difference to us since we just want to know if a string starts with a given substring.

For instance, we can write:

console.log('hello world'.indexOf('hello', 0) === 0)

to do the check.

Conclusion

There are many JavaScript string methods we can use to check whether a string starts with the given substring.

Categories
JavaScript Answers

How to Display a JavaScript Object in the Browser Console?

To make debugging easier, we can display an object we want to inspect in the console.

There are various ways to do this.

In this article, we’ll look at how to display a JavaScript object in the browser console.

console.log

The console.log method will log an object’s content directly to the console.

For instance, we can write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
console.log(obj)

We just pass in obj into console.log to log its content directly to the browser’s console.

JSON.stringify

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

For instance, we can write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
const str = JSON.stringify(obj);  
console.log(str)

Then we see:

{"a":1,"b":2,"child":{"c":3}}

in the console.

To make reading it easier, we can add indentation to the properties that are stringified.

To do this, we write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
const str = JSON.stringify(obj, undefined, 2);  
console.log(str)

The 3rd argument of JSON.stringify specifies the indentation of each stringified.

2 means 2 spaces.

So we should get:

{  
  "a": 1,  
  "b": 2,  
  "child": {  
    "c": 3  
  }  
}

logged into the console.

The console.dir Method

The console.dir method also logs an object into the console like console.log .

For instance, we can write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
console.dir(obj)

to log obj into the console.

The console.table Method

The console.table method lets us log an object’s properties in a tabular format.

For instance, if we write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
console.table(obj)

Then we get a table with the properties and values of an object in a table.

Conclusion

Browsers come with many methods to log objects into the console.

Categories
JavaScript Answers

How to Retrieve the Position of an HTML Element Relative to the Browser Window?

Retrieving the position of an HTML element relative to the browser window is something that we’ve to sometimes in our JavaScript web app.

In this article, we’ll look at ways to get the position of an HTML element relative to the browser window.

The getBoundingClientRect Method

The getBoundingClientRect method is available with HTML element node objects to let us get the position of an element.

For instance, if we have the following HTML:

<div>  
  hello world  
</div>

Then we can call getBoundingClientRect by writing:

const div = document.querySelector('div')  
const rect = div.getBoundingClientRect();  
console.log(rect.top, rect.right, rect.bottom, rect.left);

We get the div element with querySelecttor .

Then we call getBoundingClientRect to get the position.

leftand top has the x and y coordinates of the top left corner of the element.

right and bottom has the x and y coordinates of the bottom right corner of the element.

Element’s Position Relative to the Whole Page

We’ve to add scrollX and scrollY to get the element’s position relative to the whole page.

For instance, we can write:

const div = document.querySelector('div')  
const getOffset = (el) => {  
  const rect = el.getBoundingClientRect();  
  return {  
    left: rect.left + window.scrollX,  
    top: rect.top + window.scrollY  
  };  
}

console.log(getOffset(div));

scrollX returns the number of pixels that the document is currently scrolled horizontally.

And scrollY returns the number of pixels that the document is currently scrolled vertically.

offsetLeft and offsetTop

offsetLeft and offsetTop lets us get the position of the upper left corner of the element relative to the nearest parent.

For block-level elements, offsetTop, offsetLeft describe the border-box of an element relative to the offsetParent.

For inline elements, offsetTop, offsetLeft describe the positions of the first border-box.

For instance, we can use it by writing:

const div = document.querySelector('div')  
console.log(div.offsetLeft, div.offsetTop);

Conclusion

We can get the position of an element with various properties in JavaScript.

Categories
JavaScript Answers

How to Add an Image Preview When an Image File is Selected in the File Input?

Adding a preview for the selected image is something that we’ve to do sometimes in our JavaScript web app.

In this article, we’ll look at how to add an image preview to show the image the user is selected.

Add an Image Preview for a File Input

To add the image preview for a file input, first, we add the file input and the img element to display the image preview:

<form>
  <input type='file' />
  <img src="#" alt="selected image" />
</form>

We set the type to file to make the input a file input.

Next, we need to add some JavaScript code to read the file into a base64 string.

Then we can set the src property of the img element to the base64 string.

To do this, we write:

const imgInput = document.querySelector('input')
const imgEl = document.querySelector('img')

imgInput.addEventListener('change', () => {
  if (imgInput.files && imgInput.files[0]) {
    const reader = new FileReader();
    reader.onload = (e) => {
      imgEl.src = e.target.result;
    }
    reader.readAsDataURL(imgInput.files[0]);
  }
})

We get the input and img elements with document.querySelector .

Then we call addEventListener on the imgInput with a callback to let us watch for file selection.

We pass in 'change' to watch the change event, which is triggered when we select a file.

In the callback, we check is imgInput.files is present.

files has the selected files.

We get the first file with the 0 index.

Then we create the FileReader instance to read the selected file.

And we set the onload method which runs when a file is selected.

We get the e.target.result to get the file result.

The file should be read into a base64 string, which is a valid value for the src attribute of an img element.

Therefore, we can set img.src property directly to e.target.result .

And to trigger the reading of the file, we call reader.readAsDataURL method with imgInput.files[0] , which has the first selected file.

The createObjectURL Method

We can also use the createObjectURL method to create the base64 string from the selected image file.

For instance, we can write:

const imgInput = document.querySelector('input')
const imgEl = document.querySelector('img')

imgInput.addEventListener('change', () => {
  if (imgInput.files && imgInput.files[0]) {
    imgEl.src = URL.createObjectURL(imgInput.files[0]);
    imgEl.onload = () => {
      URL.revokeObjectURL(imgEl.src)
    }
  }
})

and keep the HTML code the same.

We call URL.createObjectURL with imgInput.files[0] to create the base64 string from the file object stored in imgInput.files[0] .

Then we set the onload method of the img element object, which is run when the src attribute of the img element changes.

We call URL.revokeObjectURL there to free the image object from memory.

Conclusion

We add an image preview to our JavaScript app by reading the selected image file into a base64 string and setting it as the value of the src attribute of an img element.