How do I get a key value based on an array name?
In this article firstly, we will discuss what is key and value in an array. After we will discuss different methods by which we can obtain these key-value pairs.
What are a key and value in an array?
Keys are indexes and values are factors of an associative array. Associative arrays are essential items in JavaScript in which indexes are replaced via person-defined keys. They do no longer have a length property like a normal array and can't be traversed with the usage of a normal for loop.
Here’s an example of an associative array
var arr = { "zero": 0, "one": 1, "two": 2 };
Unlike easy arrays, we use curly braces rather than square brackets. The content material or values of associative arrays is accessed through keys. Inside the above array, one, & 3 are keys, and 1, 2 & 3 are values. Those may be obtained for my part the usage of the keys() & values() strategies as proven underneath
- for (let value of Object.values(arr)) {
- alert(value);
- }
- for (let value of Object.values(arr)) {
- alert(value);
- }
- var keys = ["one", "two", "three"];
- var values = [1, 2, 3];
// create object
// Loop to insert key & value in this object one by one
for (var i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
- // output can be displayed as : one => 1 two => 2 three => 3
Different methods to obtain key-value pairs
Now that we recognize the way to get keys & values in an array, let us study the one-of-a-kind strategies to obtain key-cost pairs. Let us first store the formerly extracted keys & values in separate arrays
Using an object to store key => value pairs
In this method, we save the factors from the “keys” array & the corresponding values from the “values” array the usage of an associative array "obj"
Comments
Post a Comment