admin管理员组

文章数量:1315369

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'

/

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/dbvs5ney/

Share Improve this question asked Feb 12, 2015 at 12:21 JohanJohan 35.2k62 gold badges187 silver badges305 bronze badges 5
  • Have you tried _.constant('default') like they've got in the example? – Andy Commented Feb 12, 2015 at 12:25
  • @Andy No, I haven't. I'm using the busy example just above that as you can see. – Johan Commented Feb 12, 2015 at 12:30
  • 1 I can get it to work in my browser with your code (that fiddle doesn't work for some reason). – Andy Commented Feb 12, 2015 at 12:40
  • What version of lodash do you use? – Kiril Commented Feb 12, 2015 at 14:06
  • @Kiril 2.2.1 as you see in the Fiddle – Johan Commented Feb 12, 2015 at 14:10
Add a ment  | 

2 Answers 2

Reset to default 6

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;
  }
}

Try with newer lodash version, if you do not need specifically with version 2.2.1.

本文标签: javascriptLodash result() default valueStack Overflow