JS find specific key in array of key-value pairs
Solution 1
If you're using an additional library that supports functional programming patterns, there are somewhat more elegant ways of expressing the iteration.
For instance, with Underscore:
_.some(myArray, function(elem) {return elem.key == 'key1';});
And cookie monster correctly points out that Underscore isn't necessary at all here, because some()
is native on Array since 1.6:
myArray.some(function(elem) { return elem.key == 'key1';});
Solution 2
In other words, a better mechanism than iterating through all array elements and checking each one.
Probably not, but you can filter on the collection easily:
var coll = [{key: 'key1', value: 'value1'}
,{key: 'key1', value: 'value1'}
,{key: 'key2', value: 'value1'}]
var values = function(x) {
return Object.keys(x).map(function(k){return x[k]})
}
var result = coll.filter(function(x) {
return values(x).indexOf('key1') > -1
})
console.log(result)
//^ [{key: 'key1', value: 'value1'}
// ,{key: 'key1', value: 'value1'}]
The you can check if all the items have the value by comparing the lengths of the original collection and the filtered one:
if (result.length == coll.length) {
// All objects have a key with value "key1"
}
Or you could use Array.prototype.every
or Array.prototype.some
depending on your needs.
BaltoStar
Updated on June 04, 2022Comments
-
BaltoStar almost 2 years
JavaScript
var myArray = [{key: "key1", value: "value1"},{key: "key1", value: "value1"}];
Is there an elegant mechanism for determining if "key1" is present ?
In other words, a better mechanism than iterating through all array elements and checking each one.
Edit:
(1) keys are not necessarily unique
(2) array must be composed of key-value pairs because I need to extract KVP subsets into other arrays , re-order , de-dupe , and many other complex operations
Please re-open this question, thanks.
-
cookie monster almost 10 years+1 but you don't need libraries for that.
Array.prototype.some
is a native method. -
cookie monster almost 10 yearsHe's not explicit about it, but I'm pretty sure he's only interested in checking the value of the
key
property in each object. -
S McCrohan almost 10 yearsRight you are! I've been so used to accessing it via underscore (because I'm already using it for other things) that I'd forgotten it's widely available natively now. Editing my answer with credit to you.