I have this array:
var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});
is it possible to do get the value or a specific element by knowing the name ?
something like this:
arr['k2'].value
or
arr.get('k1')
This question is related to
javascript
jquery
json
The easiest approach which I have used is
var found = arr.find(function(element) {
return element.name === "k1";
});
//If you print the found :
console.log(found);
=> Object { name: "k1", value: "abc" }
//If you need the value
console.log(found.value)
=> "abc"
The similar approach can be used to find the values from the JSON Array based on any input data from the JSON.
Find one element
To find the element with a given name in an array you can use find
:
arr.find(item=>item.name=="k1");
Note that find
will return just one item (namely the first match):
{
"name": "k1",
"value": "abc"
}
Find all elements
In your original array there's only one item occurrence of each name.
If the array contains multiple elements with the same name and you want them all then use filter
, which will return an array.
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
arr.push({name:"k1", value:"def"});_x000D_
_x000D_
var item;_x000D_
_x000D_
// find the first occurrence of item with name "k1"_x000D_
item = arr.find(item=>item.name=="k1");_x000D_
console.log(item);_x000D_
_x000D_
// find all occurrences of item with name "k1"_x000D_
// now item is an array_x000D_
item = arr.filter(item=>item.name=="k1");_x000D_
console.log(item);
_x000D_
Find indices
Similarly, for indices you can use findIndex
(for finding the first match) and filter
+ map
to find all indices.
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
arr.push({name:"k1", value:"def"});_x000D_
_x000D_
var idx;_x000D_
_x000D_
// find index of the first occurrence of item with name "k1"_x000D_
idx = arr.findIndex(item=>item.name == "k1");_x000D_
console.log(idx, arr[idx].value);_x000D_
_x000D_
// find indices of all occurrences of item with name "k1"_x000D_
// now idx is an array_x000D_
idx = arr.map((item, i) => item.name == "k1" ? i : '').filter(String);_x000D_
console.log(idx);
_x000D_
You can't do what you're asking natively with an array, but javascript objects are hashes, so you can say...
var hash = {};
hash['k1'] = 'abc';
...
Then you can retrieve using bracket or dot notation:
alert(hash['k1']); // alerts 'abc'
alert(hash.k1); // also alerts 'abc'
For arrays, check the underscore.js library in general and the detect method in particular. Using detect you could do something like...
_.detect(arr, function(x) { return x.name == 'k1' });
Or more generally
MyCollection = function() {
this.arr = [];
}
MyCollection.prototype.getByName = function(name) {
return _.detect(this.arr, function(x) { return x.name == name });
}
MyCollection.prototype.push = function(item) {
this.arr.push(item);
}
etc...
I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter
:
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
You can see a list of supported browsers here.
In the future with ES6, you'll be able to use array.find.
I don't know anything about jquery so can't help you with that, but as far as Javascript is concerned you have an array of objects, so what you will only be able to access the names & values through each array element. E.g arr[0].name
will give you 'k1'
, arr[1].value
will give you 'hi'
.
Maybe you want to do something like:
var obj = {};
obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";
alert ("obj.k2:" + obj.k2);
To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:
Array.prototype.get = function(name) {
for (var i=0, len=this.length; i<len; i++) {
if (typeof this[i] != "object") continue;
if (this[i].name === name) return this[i].value;
}
};
this will add the get() method to all arrays and let you do what you want, i.e:
arr.get('k1'); //= abc
Source: Stackoverflow.com