Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash _.result() default value

Why doesn't lodash result method return the default value in this case?

Arguments object (Object): The object to query.

key (string): The key of the property to resolve.

[defaultValue] (*): The value returned if the property value resolves to undefined.

var result = _.result({ foo: 1 }, 'bar', 'default');

console.log(typeof _.result({ foo: 1 }, 'bar') === 'undefined') // true

console.log(result); // expected: 'default'

http://jsfiddle.net/dbvs5ney/

like image 529
Johan Avatar asked Feb 11 '23 22:02

Johan


1 Answers

Seems that the default parameter was added only in version 3.0.0
Compare the _.result implementation:
3.0.0 lodash.js

function result(object, key, defaultValue) {
  var value = object == null ? undefined : object[key];
  if (typeof value == 'undefined') {
    value = defaultValue;
  }
  return isFunction(value) ? value.call(object) : value;
}

And 2.2.1 lodash.js:

function result(object, property) {
  if (object) {
    var value = object[property];
    return isFunction(value) ? object[property]() : value;
  }
}
like image 200
Kiril Avatar answered Feb 13 '23 14:02

Kiril