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 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.

Categories
JavaScript Answers

How to Get the Last Item in a JavaScript Object?

Sometimes, we want to get the last item in a JavaScript object.

In this article, we’ll look at how to get the last item in a JavaScript object.

Get the Last Item in a JavaScript Object

To get the last item in a JavaScript object, we can use the Object.entries method to get the key-value pair arrays of an object in an array.

Therefore, we can use it to get the last item of the JavaScript object.

For instance, we can write:

const obj = {
  'a': 'apple',
  'b': 'banana',
  'c': 'carrot'
}
const entries = Object.entries(obj)
const [last] = entries.slice(-1)
console.log(last)

We have the obj object that we want to get the last property from.

Next, we call Object.entries with obj to get an array of key-value pair arrays of obj .

Then we call slice with -1 to return an array with the last entry of entries .

And we destructure that and assign it to last .

Therefore, last is:

["c", "carrot"]

Conclusion

To get the last item in a JavaScript object, we can use the Object.entries method to get the key-value pair arrays of an object in an array.

Therefore, we can use it to get the last item of the JavaScript object.

Categories
JavaScript Answers

How to Filter or Map Nodelists with JavaScript?

Sometimes, we want to filter or map nodelists with JavaScript.

In this article, we’ll look at how to filter or map nodelists with JavaScript.

Filter or Map Nodelists with JavaScript

To filter or map nodelists with JavaScript, we can use the spread operator to convert the nodelist to an array.

For instance, if we have the following HTML:

<p>
  foo
</p>
<p>
  bar
</p>

Then we can convert the nodelist with the selected p elements and call map and filter on it by writing:

const nodes = document.querySelectorAll('p')
const texts = [...nodes].map(n => n.textContent)
console.log(texts)
const filtered = [...nodes].filter(n => n.textContent.includes('foo'))
console.log(filtered)

We call document.querySelectorAll to return a nodelist with the p elements.

Then we use the spread operator to spread the items in the nodes nodelist into an array.

And then we call map to map the node array to an array of text.

Then we call filter on the array of nodes with a callback to return the nodes with textContent that includes 'foo' .

Therefore, texts is [“n foon”, “n barn”]

And filtered has an array with the first p element.

Conclusion

To filter or map nodelists with JavaScript, we can use the spread operator to convert the nodelist to an array.

Categories
JavaScript Answers

How to Search for the Immediate Children of an Element Returned by querySelector?

Sometimes, we want to search for the immediate children of an element returned by querySelector.

In this article, we’ll look at how to search for the immediate children of an element returned by querySelector.

Search for the Immediate Children of an Element Returned by querySelector

To search for the immediate children of an element returned by document.querySelector , we can use the :scope pseudoselector.

For instance, if we have the following HTML:

<div>  
  <p>  
    hello world  
  </p>  
</div>

Then we can get the p element given the div by writing:

const getChild = (elem) => {  
  return elem.querySelectorAll(':scope > p');  
};  
const div = document.querySelector('div')  
console.log(getChild(div))

We define the getChild function that calls elem.querySelectorAll to get all the p elements that are the immediate child of the given elem .

Then we get the div with querySelector and assign it to div .

And then we call getChild with div to get the p element in the div in a Nodelist.

Conclusion

To search for the immediate children of an element returned by document.querySelector , we can use the :scope pseudoselector.