user385729
user385729

Reputation: 1984

Get the object in an array of object with the key

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

Answers (2)

Adam Boduch
Adam Boduch

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:

  1. chain(): Enables explicit chaining. Otherwise, find() will return an unwrapped object, and we still have actions to perform.
  2. find(): We pass in a callback that checks for the existence of the Z key. The callback itself is constructed using higher-order function utilities:
    • ary(): Restricts the number of arguments passed to the function. We do this here because find() passes arguments that we don't care about to our callback.
    • partialRight(): Provides the 'Z' argument to the has() function. This is the rightmost argument, meaning that each item in the collection is passed as the first argument.
    • has(): Returns true if the Z key exists on an object.
  3. values(): We don't care about the object key, only it's values.
  4. first(): The 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

user3310334
user3310334

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

Related Questions