I have a feature in my application that should allow users to select items in a drop down menu and move them up and down. Once they select and click on the button I have to loop over the array of objects and pull only records that were selected in the drop down menu.
Here is an example of my code:
var selectedColumns = ['first','last','city'];
var data = [
{
first: "Mike",
last: "Ross",
dob: "05/26/1978",
city: "Washington DC",
state: "DC",
zip: 22904
},
{
first: "John",
last: "Henderson",
dob: "11/06/1988",
city: "Iowa City",
state: "IA",
zip: 52401
},
{
first: "Nina",
last: "Barkley",
dob: "01/16/1968",
city: "New York",
state: "NY",
zip: 11308
},
{
first: "Jessie",
last: "Kuch",
dob: "02/02/1956",
city: "Des Moines",
state: "IA",
zip: 55432
},
{
first: "Jenny",
last: "Terry",
dob: "012/28/1988",
city: "Miami",
state: "FL",
zip: 83943
}
];
In the selected column we only have first, last and city. Then I have to loop over data and pull only selected columns. One way to do that is like this:
for(var key in data){
for(var i=0; i<selectedColumns.length; i++){
var columnID = String(columns[i]);
console.log($.trim(data[key][columnID]));
}
}
While this solution works just fine, I'm wondering if there is better way to avoid the inner loop and improve efficiency? I use jQuery/JavaScript in my project. If anyone knows a better way to approach this problem please let me know.
data[key][columnID]
used (other than being logged to the console in the example)? \$\endgroup\$