Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using variable name in lodash collection

Question is bit crazy. Is there any possibility to using variable name instead of another, clearly, consider the following code where I have to switch over to any variable name "people" or "student" accordingly

 var people=[
      {name:"akash",age:25},
      {name:"abi",age:22}
   ];

 var student =[
     {name:"Sanjai",age:25},
     {name:"Ravi",age:35},
      {name:"Bopara",age:36}
 ];
var variables=["people","student"];

 var result= _.find(variables[0], function(o) { return o.age < 35; });
   console.log(result);  
like image 936
anisha raj Avatar asked Jun 12 '17 05:06

anisha raj


People also ask

How do you call a variable in JavaScript?

After declaring a variable or function with the var keyword, you can call it at any time by invoking its name.

How do you use variables in JavaScript objects?

Object keys can be dynamically assigned in ES6 by placing an expression in square brackets. Syntax: var key="your_choice"; var object = {}; object[key] = "your_choice"; console. log(object);

How do you assign a variable in JavaScript?

To create a variable in JavaScript, use the let keyword. To be concise, we can combine the variable declaration and assignment into a single line: let message = 'Hello! '; // define the variable and assign the value alert(message); // Hello!


1 Answers

Sure, just put variables into array instead of strings:

var variables=[people, student];

Full example:

var people=[
     {name:"akash",age:25},
     {name:"abi",age:22}
 ];

var student =[
     {name:"Sanjai",age:25},
     {name:"Ravi",age:35},
     {name:"Bopara",age:36}
 ];

var variables=[people, student];

var result= _.find(variables[0], function(o) { return o.age < 35; });

console.log(result);  
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
like image 62
Egor Stambakio Avatar answered Oct 18 '22 09:10

Egor Stambakio