I have a collection which looks like this:
var array = [
{ 'key1': 'val1'},
{ 'key2': 'val2'}
];
I want a function which takes array and value as parameters and returns key of that value (values are unique)
getKey(array, 'val1');
>>>>> output: 'key1'
I tried the following solution but it says key property is not defined:
getKey(array, value) {
var keys = [];
array.forEach(function(element) {
for (key in element) {
if(value == element[key]) {
keys.push(key);
}
}
})
return keys[0];
},
Create an inverse object with value
as key
and key
as value
. And then finally access the value
from object as key.
var array = [{ 'key1': 'val1'},{ 'key2': 'val2'}]; function getKey(arr, val) { let obj = arr.reduce((a,c) => { Object.entries(c).forEach(([k,v]) => a[v]=k); return a; }, {}) return obj[val]; } console.log(getKey(array, 'val1'));
var arr = [{ 'key1': 'val1'}, { 'key2': 'val2'}]; function getKey(data,value) { let keys=[]; data.forEach(function(element) { for (key in element) { if(element[key]==value) keys.push(key); } }); return keys } console.log(getKey(arr, 'val1'))
You can also try this:
var arr = [{ 'key1': 'val1'}, { 'key2': 'val2'}]; function getKey(arr, val) { var result = 'not found'; arr.forEach(obj => { for (var key in obj) { if(obj[key] === val) result = key; } }); return result; } console.log(getKey(arr, 'val1')); console.log(getKey(arr, 'value'));
In pure JS you can take all the entries, flatten them and simply search the value in all couples and if found then just take the first entry of that couple.
[].concat(...array.map(Object.entries)).find(a=>a[1]=='val1')[0]
Here is an working example:
var array = [{'key1': 'val1'}, {'key2': 'val2'}, {'key3': 'val3'}], getKey = (arr,v)=>[].concat(...arr.map(Object.entries)).find(a=>a[1]==v)[0]; console.log(getKey(array, 'val2')); console.log(getKey(array, 'val3'));
However, I will suggest you to use lodash
(or underscore
, or lazy
) to make it more cleaner and simple.
Here is a lodash approach:
_.findKey(_.merge({}, ...array), s=>s=='val1')
Here is a woking example:
var array = [{'key1': 'val1'}, {'key2': 'val2'}, {'key3': 'val3'}], getKey = (arr,v)=>_.findKey(_.merge({}, ...arr), s=>s==v); console.log(getKey(array, 'val2')); console.log(getKey(array, 'val3'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.