Reputation: 1984
So I have an array of objects and I want to get the object with the key "Z".
Obviously I can just loop through the array and check each key one by one and grab the one which matches, but I was thinking that there is probably a better way than my current approach:
for (var i = 0; i < data.length; i++) {
if (Object.keys(data[i]).toString() == "z") {
return data[i].z;
break;
}
}
My data:
"data": [
{ "X": { "foo": "bar1" } },
{ "Y": { "foo": "bar2" } },
{ "Z": { "foo": "bar3" } }
]
Desired Output:
{
"foo": "bar3"
}
Upvotes: 0
Views: 51
Reputation: 11211
Using lodash, you could do something like:
var collection = [
{ X: { foo: 'bar1' } },
{ Y: { foo: 'bar2' } },
{ Z: { foo: 'bar3' } }
];
_(collection)
.chain()
.find(_.ary(_.partialRight(_.has, 'Z'), 1))
.values()
.first()
.value()
// → { foo: 'bar3' }
An outline of what this chain is doing:
find()
will return an unwrapped object, and we still have actions to perform.Z
key. The callback itself is constructed using higher-order function utilities:
find()
passes arguments that we don't care about to our callback.'Z'
argument to the has()
function. This is the rightmost argument, meaning that each item in the collection is passed as the first argument.Z
key exists on an object.values()
function returns a collection, but we only want the first item in it. There should only ever be one item in the collection.Upvotes: 0
Reputation:
Instead of an array of objects, you could replace it with an object:
"data": {
"X": { "foo": "bar1" },
"Y": { "foo": "bar2" },
"Z": { "foo": "bar3" }
}
And then access your object like so:
data['Z']
as you can see, much neater.
I'm guessing you used an array originally for easy appending and so on, but it's just as easy with an object:
data['A'] = { "foo": "bar4" };
will create key "A"
in data, and you can still loop through your object using for (... in ...)
loops, i.e:
for (key in data) {
console.log(data[key].foo);
}
should print
bar1
bar2
bar3
bar4
Upvotes: 2