Bogac
Bogac

Reputation: 3707

How to chain functions from array to object in Lodash

I was hoping this work, but it didn't:

var myName = _(myArray)
    .find({ "ID": 5 })
    .get("Name");

Basically I want to find one element within an array, where ID property is equal to 5 and then get value of "Name" property of that.

What am I missing ?

Upvotes: 1

Views: 1105

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

Below, I have written three different calls which will all return the desired data. As they say, there is more than one way to skin a cat, when it comes to programming. You must choose the most effective or efficient for your needs.

The two latter function below, which uses the _.result function, have been adapted from the lodash documentation. You can use result as a replacement for _.get().

_.result(object, path, [defaultValue])

This method is like _.get except that if the resolved value is a function it’s invoked with the this binding of its parent object and its result is returned.

Arguments

  • object (Object): The object to query.
  • path (Array|string): The path of the property to resolve.
  • [defaultValue] (*): The value returned if the resolved value is undefined.

Returns

  • (*): Returns the resolved value.

var myArray = [
  { ID : 0,  Name : 'Foo' },
  { ID : 1,  Name : 'Bar' },
  { ID : 5,  Name : 'Baz' },
  { ID : 10, Name : 'Oof' }
];

// Convienience function to print to the DOM. (Only for debugging)
function print() {
  document.body.innerHTML += '<p>' + [].join.call(arguments, ' ') + '</p>';
}

// Find item using chaining with `_.find()` and `_.get()`.
print(
  '<span class="lbl">Chain + Find + Get:</span>',
  _(myArray).chain().find({ 'ID' : 5 }).get('Name')
);

// Find item using a predicate (function).
print(
  '<span class="lbl">Find (Function Predicate) + Result:</span>',
  _.result(_.find(myArray, function(chr) {
    return chr.ID === 5;
  }), 'Name')
);

// Find item using the `_.matches()` callback shorthand.
print(
  '<span class="lbl">Find (Object Predicate) + Result:</span>',
  _.result(_.find(myArray, { 'ID' : 5 }), 'Name')
);
.lbl {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

You don't need to use .get() here. .find() returns the matching object, so to pull its Name property you can simply reference .Name on that object:

var myName = _(myArray).find({ "ID": 5 }).Name;

This will only work if the .find() call succeeds. You may want to store the result of the .find() in a variable, then check if that isn't null before returning the Name property:

var match = _(myArray).find({ "ID": 5 }),
    myName;

if (match) {
    myName = match.Name;
}

Upvotes: 1

Related Questions