Get an object in an array with one of your fields
Sorry I'm new to JS; I have an array of objects; how can i get the name of an object that has key "user_key3" and obviously has no loop and has a condition.
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}]
Please let me know if you need more clarification.
thank
source to share
You will have to iterate over and check the key
var user_name;
for (var i=0; i<arr.length; i++) {
if ( arr[i].key === 'user_key3' ) {
user_name = arr[i].name;
break;
}
}
You edited the question to include
obviously without a loop and has the condition
but loop and condition is by far the most efficient and cross-browser way to do it, so why don't you "explicitly" want it?
source to share
You can do it functionally like this
var name;
arr.forEach(function(currentObject) {
if (currentObject.key === "user_key3") {
name = currentObject.name;
}
});
If you want to short-circuit on the first match, you can use Array.prototype.some
like this
var name;
arr.some(function(currentObject) {
if (currentObject.key === "user_key3") {
name = currentObject.name;
return true;
}
return false;
});
source to share
The OP mentioned is obviously no loop and has a condition . I would do it like below:
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}];
var keyValMap = arr.map(function(n) { return n.key } );
var arrIndex = keyValMap.indexOf('user_key3');
alert(arr[arrIndex].name);
source to share
In general, finding an element that satisfies some arbitrary property in an array requires you to iterate over the array:
function find(arr, name) {
for (var i=0; i<arr.length; i++) {
if ( arr[i].key === name ) {
return arr[i];
}
}
}
Then, to find him,
var obj = find(arr, 'user_key3');
Using more functional solutions to find an item is fine too, but you end up getting stuck in a loop anyway.
However, if you are searching by key, then an array of key-value pairs is not the best data structure. I would suggest using the object directly:
var map = {
'user_key1': 'user1',
'user_key2': 'user2',
'user_key3': 'user3'
}
Then the search is simple:
map['user_key3'];
source to share
You cannot do this kind of thing with objects in Javascript. Although here you have a combination of callbacks and a loop:
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}];
arr.forEach(function(elme){
for(var g in elme)
{
if(elme[g] == 'user_key3')
{
console.log("Found the value: "+g+" : "+elme[g]);
};
}
});
source to share