How can you retrieve the key of an element stored in a JavaScript array?

In my PHP code, I am able to obtain the key from an array by searching for a specific value.

<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');


while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}

?>

However, as I delve into learning JavaScript, I have been unable to find a solution to achieve the same functionality. As a beginner in JavaScript programming, I'm facing some challenges.

What is the method to retrieve the key based on a given value inside an array in JavaScript?

I've attempted using methods like .indexOf() or .findIndex() without success.

var array = [];
array['key'] = 'Value';
array['car'] = 'Ferrari';
array['car2'] = 'BMW';
console.log(key='Ferrari'??);

If the value is 'Ferrari', how can I return the key 'car'?

Furthermore, should I utilize Arrays or Classes to address this issue? Is it feasible to fetch the key of a Class?

var pessoas = {'car': 'Ferrari', 'car2':'BMW'};

Answer №1

Arrays operate with numeric indexes and do not have keys. When a string is passed to an Array, it creates a new property for the Array object rather than a new item in the Array data (such as the .length which is a property of an Array).

var array = [];
// The following 3 lines don't add indexed values to the array:
array['key'] = 'Value';
array['car'] = 'Ferrari';
array['car2'] = 'BMW';

// This is shown here:
console.log(array.length);  // 0

// Instead, they create new properties on the Array instance:
console.log(array.car2); // "BMW"

If you require keys, it's best to use an object, whose structure is like this:

 {key: keyValue, key: keyValue, key:keyValue ...}

where the key is always a string, so no quotes are needed around the key name.

var pessoas = {car: 'Ferrari', car2:'BMW'};

console.log("The second car is: " + pessoas.car2);

console.log("The keys and key names are: ");
for (var prop in pessoas){
  console.log(prop + " : " + pessoas[prop]);
}

Answer №2

To effectively store the PHP equivalent of arrays with keys in JavaScript, it is recommended to use Objects instead of arrays. When non-numeric keys are added to an array in JS and then the .length property is used, it will return 0. This can cause issues with built-in functions like .filter, .find, and .map.

//preferred method
let people = [];
people["car1"] = "Ferrari";
people["car2"] = "BMW";
//a safer approach - both methods work
people = {'car': 'Ferrari', 'car2':'BMW'};
function getKeyByValue(obj, value) {
  return Object.keys(obj).find(key => obj[key] === value);
}

console.log(getKeyByValue(people, 'BMW'));

Another way to handle string-keyed arrays is by converting them into objects as shown below:

 
    function getKeyByValue(obj, value) {
        return Object.keys(obj).find(key => obj[key] === value);
      }
    var arrayToObject = (array) => Object.keys(array).reduce((acc, curr) => (acc[curr] = array[curr], acc), {});

    let people = [];
    people["car1"] = "Ferrari";
    people["car2"] = "BMW";
    people.push("correctArray");
    people = arrayToObject(people);
    console.log(getKeyByValue(people, 'BMW'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlimited Possibilities in Designing Shared React Components

Seeking the most effective strategies for empowering developers to customize elements within my React shared component. For example, I have a dropdown and want developers to choose from predefined themes that allow them to define highlight color, font siz ...

Display the contents of a div when it is shown within a tabbed page

Looking for some advice on my tabbed web page with a toggle using jQuery. The tab switch is working smoothly, but now I want to load div content dynamically with AJAX only when the user clicks on a tab for the first time. My idea is to use a flag as an att ...

The error message "TypeError: language.map is not a function" occurred while attempting to retrieve data with

I have created a component using MUI for tables. I am fetching data from an API and then using the map method to display the data. However, I encountered an error message that reads: TypeError: language.map is not a function When I try putting "language" ...

Error: Unspecified (reading 'map'). Utilizing '&&' triumphs in compiling but results in no array being shown

As a beginner student in next-js, I am currently focused on learning about databases and calling arrays. In the files structure & script provided (in this image), I am attempting to call arrays from /data. The issue with the script is that it is ...

How can I achieve a partial match for an object property in a JavaScript loop

How can I reformat this array of objects const arr = [{ my_first_name_1: { value: 'jane' }, my_last_name_1: { value: 'anderson' } }, { my_first_name_2: { value: 'alex' }, my_last_name_2: { value ...

Establishing the controller to set the default order

Would appreciate some assistance with what may appear to be a beginner's question, please? This is the HTML code I'm working with: <!doctype html> <html> <head> <title>Starting Angular</title> </head> < ...

Issues arise with AJAX post

I have run into an issue with my jQuery and Codeigniter setup while trying to update the database via AJAX. Despite having the following code in place, nothing seems to be happening or getting sent to my controller when the button is clicked... Snippet of ...

Identifying Master Page Controls Post-Rendering

Within my asp.net projects, I have noticed a discrepancy in the control id on the master page's Contentplaceholder1. On my local server, the id appears as "ctl00_Contentplaceholder1_control" after rendering. However, when the application is deployed t ...

Is there a way to retrieve particular information from an array in the Facebook Graph API?

I have successfully transformed my object data into an array and now I am facing some difficulties in extracting specific parts from the multidimensional array. Any kind of assistance would be highly appreciated, thank you. /* SDK version 4.0.0 written i ...

What is the manner in which web data is presented on a web browser interface?

After reading information on Mozilla's website, I have a question regarding the functionality of client-side code. In web development, terms like server-side and client-side code are commonly used. Client-side code refers to the code that runs on t ...

Having trouble retrieving the array value from xpath

Here is the content of my reg.xml file: <childrens> <child_4 entity_id="4" value="Activities" parent_id="2"> <child_10066 entity_id="10066" value="Physical1" parent_id="4"> <child_10067 entity_id="10067" value="Cricket" parent ...

Can you share the method for concatenating an object at a specific index within an Array using JavaScript?

Currently, I have an array arr = [object1, object2, object3]. After removing the second index, the array now looks like arr = [object1, object3], and I am looking to add back the removed object2 at its original position in the array so that it becomes a ...

Detecting Text Changes in Quill JS on Form Submission

I'm utilizing Quill (Rich Text) and am searching for a way to detect whether the text has been altered when the page submits a form. My experience with Quill is limited, so I've been investigating the available events here. The text-change event ...

How can I prevent the interpolation of "${variable}" in HTML when using AngularJS?

I need to display the string ${date} in a div element: <div>please substitute the ${date} as the tag for the name</div> The displayed content should be: please use the ${date} as the substitute tag to the name. However, the browser interpre ...

Issue encountered while trying to download JSON file

I have been attempting to download JSON data into a JSON file using the code snippet below, but all it does is present me with a blank page in Internet Explorer. I am in search of a solution to download the JSON file without triggering any events on the ...

What is the best way to incorporate tailored validation into reactive forms in Angular?

I'm facing an issue with my form where I'm trying to display a specific error message based on certain conditions. Currently, my form is functioning but it's throwing a type error stating "undefined is not an object". I'm struggling to ...

Issue (@websanova/vue-auth): http plugin has not been properly configured in drivers/http/axios.js

I've been working on integrating vue-auth into my laravel-vue application, but I'm encountering some console errors: Error (@websanova/vue-auth): drivers/http/axios.js: http plugin has not been set. Uncaught TypeError: this.plugins.http is u ...

Ways to activate a click event on a parent div without affecting a particular child element in Angular

I am working on an Angular component that consists of nested div elements. My goal is to trigger a click event on the parent div, however, I want to ensure that if the menu child div is clicked, the parent div's click event should not be triggered. C ...

Utilizing Multiple UV maps in Three.js for Enhanced Object Texturing

I'm currently exploring how to apply two different textures on the front and back of a box. The issue I'm facing is that when I scale my box (using ExtrudeGeometry), the UV maps do not update as expected. As a result, I've resorted to defini ...

Once the second form is displayed, a problem arises with the functionality of the submit button on the newly created form

I am encountering an issue with a form that appears after the initial form submission. The first form successfully submits and generates a new form underneath based on the number entered. However, when the second form that appears is submitted, the intende ...