-2
var fields = {
    100: 'Harry',
    200: 'Zack'
};

var required = 200;

How can I get the output of Zack? I know there is a utility in lodash but not quite sure how to use it.

GG.
  • 19,404
  • 12
  • 77
  • 125
endtoend6
  • 65
  • 1
  • 10
  • 2
    Is your real situation more complicated than this? Lodash isn't necessary, just plain javascript should work: fields[required] – Dustin Hodges Dec 20 '16 at 20:46
  • I suggest you go back and review a basic JS tutorial, which will help you understand how to access a property on an object. You could start [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript#Objects). –  Dec 20 '16 at 20:56

3 Answers3

1

You can make use of plain Javascript.

var result = fields["200"]

or

var result = fields[required]

The important thing to note is that Javascript properties are internally stored as string.

Abhinav Galodha
  • 8,555
  • 2
  • 31
  • 39
1

You could use get:

var result = _.get(fields, required);
Gruff Bunny
  • 27,146
  • 10
  • 69
  • 58
  • And how is this different/better than `fields[required]`? –  Dec 20 '16 at 20:48
  • 1
    OP asked about a Lodash solution. – Gruff Bunny Dec 20 '16 at 20:51
  • But he doesn't need lodash. –  Dec 20 '16 at 20:53
  • The difference is `_.get(object, 'a.b.c', 'default')`, support for path and default value. But this is unnecessary complexity for the question asked, though it answers the question in terms of Lodash correctly. – Emile Bergeron Dec 20 '16 at 20:56
  • 1
    You don't need lodash for anything as you could write everything in plain javascript. I did not presume that he could do without lodash as it may be a requirement to use it e.g an assignment. – Gruff Bunny Dec 20 '16 at 20:57
  • So are you proposing that instead of writing `obj.a.b.c` he write `_.get(obj, 'a.b.c')`? That's insane. The tone of his question certainly does not suggest that using lodash is a requirement; it's fairly clear he doesn't know how to access properties on an object, and just imagines that he might need to use to lodash to do that. –  Dec 20 '16 at 20:57
  • 1
    The question is explicitly about lodash. It is tagged as lodash, it has lodash in the question text and heading. Not sure how you can suggest it's not. – Gruff Bunny Dec 20 '16 at 21:04
  • Though overkill for OP, it's what he asked. The answer doesn't deserves a downvote. Downvote the question for a lack of research. – Emile Bergeron Dec 20 '16 at 21:28
1

fields[required] will work.

console.log(fields[required]);
Ninja
  • 1,920
  • 1
  • 22
  • 27