Home > Enterprise >  Return the key from a JavaScript array?
Return the key from a JavaScript array?

Time:06-17

Using PHP I can return the key by looking up the value inside an array.

<?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);
}

?>

But I'm learning javascript, I've searched and haven't found a solution, I'm still a beginner.

How can I return the key by fetching the value within a given array?

I've already tried using its functions: .indexOf() or .findIndex()

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

How to Return 'car' if Value = 'Ferrari' ?

another doubt in this case is it better to use Array or Class? Is it possible to return the class key?

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

CodePudding user response:

Arrays don't have keys, only numeric indexes. When you pass a string to an Array, you are actually creating a new property for the Array object, not a new item in the Array data (for example, .length is a property of an Array, not an indexed value).

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

// Which is proven here:
console.log(array.length);  // 0

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

If you need keys, use an object, which is structured as follows:

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

where the key is always a string, so quotes around the key name are not necessary.

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]);
}

CodePudding user response:

var pessoas = {'car': 'Ferrari', 'car2':'BMW'};
function getObjKey(obj, value) {
  return Object.keys(obj).find(key => obj[key] === value);
}


console.log(getObjKey(pessoas, 'BMW'));

  • Related