Categories
JavaScript Answers

How to Automatically Add Properties to an Object that is Undefined with JavaScript?

Sometimes, we want to automatically add properties to an object that is undefined with JavaScript.

In this article, we’ll look at how to automatically add properties to an object that is undefined with JavaScript.

Automatically Add Properties to an Object that is Undefined with JavaScript

To automatically add properties to an object that is undefined with JavaScript, we can use the hasOwnProperty method to check if a property exists.

It’ll return true if it exists and false otherwise.

If it returns false , then we can set the property value to the value we want.

For instance, we can write:

const test = {}  
if (!test.hasOwnProperty('hello')) {  
  test.hello = {};  
}  
test.hello.world = "Hello World!"

We have the test object that we want to add the hello property to if it doesn’t exist.

We check that it doesn’t exist with !test.hasOwnProperty(‘hello’) .

And if that’s true , we set test.hello to an empty object.

Then we set test.hello.world to “Hello World!” .

The hasOwnProperty method can be overridden easily since it’s inherited from the Object constructor.

Therefore to make sure we always call the right hasOwnProperty method, we can write:

const test = {}  
if (!Object.prototype.hasOwnProperty.call(test, 'hello')) {  
  test.hello = {};  
}  
test.hello.world = "Hello World!"

We call Object.prototype.hasOwnProperty.call with test to do the same thing as test.hasOwnProperty , but we make sure that we always call the right one from the Object constructor.

Conclusion

To automatically add properties to an object that is undefined with JavaScript, we can use the hasOwnProperty method to check if a property exists.

It’ll return true if it exists and false otherwise.

If it returns false , then we can set the property value to the value we want.

Categories
JavaScript Answers

How to Handle Function KeyPress Events (F1-F12) using JavaScript?

Sometimes, we want to handle function keypress events (F1-F12) using JavaScript.

In this article, we’ll look at how to handle function keypress events (F1-F12) using JavaScript.

Handle Function KeyPress Events (F1-F12) using JavaScript

To handle function keypress events (F1-F12) using JavaScript, we can add a key-down event handler.

And in it, we call preventDefault to stop the default action from executing.

And then we can do what we want instead when a function key is pressed.

For instance, we can write:

window.onkeydown = (evt) => {  
  switch (evt.keyCode) {  
    //ESC  
    case 27:  
      evt.preventDefault();  
      console.log("esc");  
      break;  
    //F1  
    case 112:  
      evt.preventDefault();  
      console.log("f1");  
      break;  
    default:  
      return;  
  }  
};

to set the window.onkeydown property to an event handler that checks what the keyCode property is pressed with a switch statement.

keyCode returns a numeric code for the key that’s pressed.

Keycode 27 is the escape key, and 112 is the F1 key.

We call evt.preventDefault to stop the default action in each case clause.

So pressing F1 will stop the help screen from displaying and will log 'f1' instead.

Conclusion

To handle function keypress events (F1-F12) using JavaScript, we can add a key-down event handler.

And in it, we call preventDefault to stop the default action from executing.

And then we can do what we want instead when a function key is pressed.

Categories
JavaScript Answers

How to Find the Index of an Object by Key and Value in a JavaScript Array?

Sometimes, we want to find the index of an object by key and value in a JavaScript array.

In this article, we’ll look at how to find the index of an object by key and value in a JavaScript array.

Find the Index of an Object by Key and Value in a JavaScript Array

To find the index of an object by key and value in a JavaScript array, we can use the JavaScript array’s findIndex method.

For instance, we can write:

const peoples = [{
    "attr1": "bob",
    "attr2": "pizza"
  },
  {
    "attr1": "john",
    "attr2": "sushi"
  },
  {
    "attr1": "larry",
    "attr2": "hummus"
  }
];
const index = peoples.findIndex((person) => {
  return person.attr1 === "john"
});
console.log(index)

We create the peoples array with objects that have the attr1 and attr2 properties.

Then we call findIndex on peoples with a callback that returns person.attr1 === 'john' .

This will return the index of the first object that has the attr1 property value set to 'john' .

Therefore, index is 1 as a result.

Conclusion

To find the index of an object by key and value in a JavaScript array, we can use the JavaScript array’s findIndex method.

Categories
JavaScript Answers

How to Change the Placeholder Text of an Input Element with JavaScript?

Sometimes, we want to change the placeholder text of an input element with JavaScript.

In this article, we’ll look at how to change the placeholder text of an input element with JavaScript.

Change the Placeholder Text of an Input Element with JavaScript

To change the placeholder text of an input element with JavaScript, we can set the placeholder property of an element.

For instance, if we have the following input elements:

<input type="text" name="Email" placeholder="Some Text">
<input type="text" name="firstName" placeholder="Some Text">
<input type="text" name="lastName" placeholder="Some Text">

Then we can set the placeholder attribute value for each input element by writing:

document.getElementsByName('Email')[0].placeholder = 'new text for email';
document.getElementsByName('firstName')[0].placeholder = 'new text for fname';
document.getElementsByName('lastName')[0].placeholder = 'new text for lname';

We call document.getElementsByName to get the element with the given name attribute value.

Then we use index 0 to get the first element returned.

Next, we set the placeholder property of each to a string with the new placeholder property value.

And now we see the text we set in the JavaScript code is displayed as the placeholder text.

Conclusion

To change the placeholder text of an input element with JavaScript, we can set the placeholder property of an element.

Categories
JavaScript Answers

How to Sort Arrays in JavaScript by Object Key Value?

Sometimes, we want to sort arrays in JavaScript by object key value.

In this article, we’ll look at how to sort arrays in JavaScript by object key value.

Sort Arrays in JavaScript by Object Key Value

To sort arrays in JavaScript by object key value, we can use the JavaScript array’s sort method.

For instance, we can write:

const arr = [{
  name: "alex"
}, {
  name: "clex"
}, {
  name: "blex"
}];
const sorted = arr.sort((a, b) => (a.name > b.name ? 1 : -1))
console.log(sorted)

to sort the arr array by the value of the name properties.

We call arr.sort with a callback that compare the name properties of entries a and b in the arr object.

If a.name is bigger than b.name , we return 1.

Otherwise, we return -1.

The comparison operator will compare 2 string’s by their lexical order.

Therefore, sorted is:

[
  {
    "name": "alex"
  },
  {
    "name": "blex"
  },
  {
    "name": "clex"
  }
]

Conclusion

To sort arrays in JavaScript by object key value, we can use the JavaScript array’s sort method.