Categories
JavaScript Answers

How Create an Associative Array or Hash in JavaScript?

In many programming languages, associative arrays let us store key-value pairs in our JavaScript app.

In this article, we’ll look at how to create associative arrays or a hash with JavaScript.

Create Associate Arrays with Objects

One way to create associative arrays is with JavaScript objects.

This is because we can remove JavaScript object properties dynamically.

The property name is the key and the value is the value.

For instance, we can write:

const dictionary = {}
dictionary.a = 1
dictionary.b = 2
console.log(dictionary)

to create the dictionary object with properties a and b .

dictionary is {a: 1, b: 2} .

We can also put property names in square brackets as strings.

For instance, we can write:

const dictionary = {}
dictionary['a'] = 1
dictionary['b'] = 2
console.log(dictionary)

This lets us add property names dynamically in our code.

Then to iterate through the object, we can use the Object.keys , Object.values or Object.entries methods.

Object.keys returns an array of keys of an object.

Object.values returns an array of values of an object.

Object.entries returns an array of array of key-value pairs of an object.

For instance, we can write:

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const key of Object.keys(dictionary)) {
  console.log(key, dictionary[key])
}

Then we get:

a 1
b 2

from the console log.

key has the key that’s being iterated through with the for-of loop.

We can loop through the values with Object.values :

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const value of Object.values(dictionary)) {
  console.log(value)
}

So we get:

1
2

from the console log.

And we can loop through the key-value pairs with Object.entries :

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const [key, value] of Object.entries(dictionary)) {
  console.log(key, value)
}

We destructure the key and value from the array being iterated through to get the key and value.

And so we get:

a 1
b 2

Since Object.keys , Object.values or Object.entries methods return arrays, we can get the length with the length property of what they return.

Maps

ES6 comes with the Map constructor to let us create associative arrays or hashes.

For instance, we can use it by writing:

const map = new Map()
map.set('a', 1)
map.set('b', 2)

We call the set method with the key and value respectively to add the entry.

Then we can iterate through it with the for-of loop since it’s an iterable object:

for (const [key, value] of map) {
  console.log(key, value)
}

We can use the get method with the key to getting the value for the given key:

const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map.get('a'))

We pass in 'a' to return 1, which is what we have on the map.

To get the size, we use the size property:

const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map.size)

And the console log should show 2.

Conclusion

We can create an associative array or hash with JavaScript objects with maps.

Categories
JavaScript Answers

How to Set the Value of an Input Field with JavaScript?

One way to set the value of an input field with JavaScript is to set the value property of the input element.

For instance, we can write the following HTML:

<input id='mytext'>

Then we can set the value property of the input by writing:

document.getElementById("mytext").value = "My value";

Call the setAttribute Method

Also, we can call the setAttribute method to set the value attribute of the input element.

For instance, we can write:

document.getElementById("mytext").setAttribute('value', 'My value');

We call setAttribute with the attribute name and value to set the value attribute to 'My value' .

Setting the value Property of an Input in a Form

We can also get the input element by using the document.forms object with the name attribute value of the form and the name attribute value of the input element.

For example, we can write the following HTML:

<form name='myForm'>
  <input type='text' name='name' value=''>
</form>

Then we can use it by writing:

document.forms.myForm.name.value = "New value";

The form name value comes first.

Then the name value of the input element comes after it.

document.querySelector

We can use the document.querySelector method to select the input.

For instance, we can write the following HTML:

<input type='text' name='name' value=''>

Then we can write:

document.querySelector('input[name="name"]').value = "New value";

to get the element with querySelector .

We select the input with the name attribute by putting the name key with its value in the square brackets.

Conclusion

We can set the value of an input field with JavaScript by selecting the element.

Then we can set the value attribute by setting the value property or calling setAttribute .

Categories
JavaScript Answers

How to Get a Key in a JavaScript Object by its Value?

Sometimes, we may want to get the key of a JavaScript object by its value.

In this article, we’ll look at how to get a key in a JavaScript object by its value.

Object.keys and Array.prototype.find

We can use the Object.keys method to return an array of non-inherited string keys in an object.

And we can use the JavaScript array’s find method to return the first instance of something that meets the given condition in an array.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const key = Object.keys(object).find(key => object[key] === value);
console.log(key)

We have the object object that we want to search for the key in.

And value is the value of the key that we want to search for.

We get all the keys of object with Object.kets .

Then we call find with a callback that returns object[key] === value .

key is the object key being iterated through to find the key name for the given value .

Therefore, we should see that key is 'b' from the console log.

Object.keys and Array.prototype.filter

We can replace the find with filter and destructure the result from the array returned by filter .

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const [key] = Object.keys(object).filter(key => object[key] === value);
console.log(key)

And we get the same result for key as in the previous example.

Object.entries and Array.prototype.find

We can use the Object.entries method to return an array of arrays of key-value pairs of an object.

Therefore, we can use the returned array to find the key of the object with the given value.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const [key] = Object.entries(object).find(([, val]) => val === value);
console.log(key)

We call find with a callback that has the parameter with the val variable destrutured from the parameter.

val has the value of the in the key-value pair array.

So when we return val === value , we return the same boolean expression as the first example.

From the returned result of find , we can get the key of from the returned key-value pair by destructuring it.

And so we get the same value of key logged in the console log.

Conclusion

We can find a key that has the given value by using native JavaScript object methods.

Categories
JavaScript Answers

How to Prepend and Append an Element with Regular JavaScript?

Sometimes, we want to prepend or append a child element in a parent element on our web page.

In this article, we’ll look at how to prepend and append an element with regular JavaScript.

Prepend an Element

We can prepend an element by using the insertBefore method.

For instance, if we have the following HTML:

<div id='parent'>  
  <p>  
    hello world  
  </p>  
</div>

Then we can prepend an element before the p element in the div by writing:

const parent = document.getElementById("parent");  
const child = document.createElement("div");  
child.innerHTML = 'Are we there yet?';  
parent.insertBefore(child, parent.firstChild);

We get the div with document.getElementById .

Then we create a div with document.createElement .

And then we add some content to the child div by setting the innerHTML property.

Finally, we call parent.insertBefore with the child element we want to insert and parent.firstChild to prepend child before the first child node of parent .

Append an Element

We can append an element into a container element by using the appendChild method.

For instance, if we have the following HTML:

<div id='parent'>  
  <p>  
    hello world  
  </p>  
</div>

Then we can add a child after the p element by writing:

const parent = document.getElementById("parent");  
const child = document.createElement("div");  
child.innerHTML = 'Are we there yet?';  
parent.appendChild(child);

The first 3 lines are the same as the previous example.

The only difference is that we call parent.appendChild with child to add child after the p element.

Conclusion

We can use the insertBefore method to prepend an element as the first child element.

And we can use the appendChild method to add a child element as the last child of the parent element.

Categories
JavaScript Answers

How to Format Moment.js as a 24-Hour Format Date-Time?

Sometimes, we want to format a moment.js date as a 24-hour date-time.

In this article, we’ll look at how to format a moment.js date as a 24-hour date-time.

Use the HH Formatting Tag

We can use the HH formatting tag to format the hour into 24-hour format.

For instance, we can write:

const date = moment("01:15:00 PM", "h:mm:ss A").format("HH:mm:ss")  
console.log(date)

Then we get:

'13:15:00'

as a result.

Use the H Formatting Tag

Alternatively, we can use the H formatting tag to format the hour to 24-hour format.

For instance, we can write:

const date = moment("01:15:00 PM", "h:mm:ss A").format("H:mm:ss")  
console.log(date)

Then we also get:

'13:15:00'

as a result.

Conclusion

We can use the H or HH formatting tag to format the hour of a date-time as a 24-hour format time.