0

I have feature in my application that should allow users to select items in 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 drop down menu. Here is 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 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.lenght; 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 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. Thank you.

espresso_coffee
  • 5,076
  • 9
  • 53
  • 124
  • 1
    @epascarello Any other smart comments? – espresso_coffee Nov 09 '18 at 19:32
  • 3
    Hey espresso_coffee. StackOverflow is generally for code that *doesn't* work. If your code is working as you'd like, and you're just looking for ways to *improve* it (either in how it's written, or efficiency), you may have some better luck over at **[Code Review](https://codereview.stackexchange.com/)**. – Tyler Roper Nov 09 '18 at 19:34
  • @TylerRoper Thanks for letting me know. I did not know about Code Review site. – espresso_coffee Nov 09 '18 at 19:34
  • Not entirely clear exactly what it is you are trying to accomplish here either. *"pull selected column"* could use better definition – charlietfl Nov 09 '18 at 19:36
  • @charlietfl to pull data for the items that are selected in array. – espresso_coffee Nov 09 '18 at 19:37
  • Well the code would not work with that typo..... If you can use ES6 there is a nicer way, if you can't than you can loop, just what you use to loop is up to you. – epascarello Nov 09 '18 at 19:38
  • Maybe others get it....is still quite vague to me what expected results are – charlietfl Nov 09 '18 at 19:40
  • @charlietfl Try to run the code that might help you understand the way it should work. – espresso_coffee Nov 09 '18 at 19:41
  • @charlietfl It's like a database of people with all of the columns listed in `data`. The user can select which columns they'd like to return, ie, "I want to see everyone's first name." would be `selectedColumns = ['first']`. – Tyler Roper Nov 09 '18 at 19:41
  • As Tyler mentioned, this would be better suited for Code Review. Asking for a "better way" is both asking for opinionated answers and too broad. – Taplar Nov 09 '18 at 19:42
  • I'm curious why you need to create a subset of the data, a server can pick what it needs and a UI can display what it chooses? – Dominic Nov 09 '18 at 19:42
  • https://stackoverflow.com/questions/25553910/one-liner-to-take-some-properties-from-object-in-es-6 – epascarello Nov 09 '18 at 19:43
  • @Dominic This application is developed by someone else and I took over recently. They decided to use JSON files instead of communicating with database directly. In one had make sense because data changes only once a month. – espresso_coffee Nov 09 '18 at 19:43
  • I'm voting to close this question as off-topic because it belongs on the CodeReview SE site. – pushkin Nov 09 '18 at 19:58
  • @pushkin Not sure why questions has to be closed since I'm getting plenty of useful feedback from the users. – espresso_coffee Nov 09 '18 at 19:59
  • 1
    @pushkin Feel free to recommend the OP post on CR but in the future, please don't use the existence of the Code Review site as a reason to close a question. Evaluate the request and use a reason like *too broad*, *primarily opinion-based*, etc. Then you can mention to the OP that it can be posted on Code Review if it is [on-topic](https://codereview.stackexchange.com/help/on-topic). Please see the section **What you should not do** in [this answer to _A guide to Code Review for Stack Overflow users_](https://codereview.meta.stackexchange.com/a/5778/120114) – Sᴀᴍ Onᴇᴌᴀ Nov 09 '18 at 20:03
  • @SᴀᴍOnᴇᴌᴀ Noted - retracted vote – pushkin Nov 09 '18 at 20:05
  • 1
    Was just typing out something similar to @SᴀᴍOnᴇᴌᴀ . A question being "better suited for Code Review" is not reason enough **on its own** for a closure vote. And it's not to pick on pushkin at all, I simply see it so frequently and feel that reinforcing this can't be stressed enough. :) – Tyler Roper Nov 09 '18 at 20:06

5 Answers5

4

You can use Array.map, Array.reduce and Object.assign

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

let result = data.map(o => selectedColumns.reduce((a,c) => Object.assign(a,{[c]:o[c]}), {}));
console.log(result);

EDIT

var selectedColumns = ['dob','last','city'];
var data = [{first: "Mike",last: "Ross",dob: "01/01/1900",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}];

let result = data.map(o => selectedColumns.reduce((a,c) => {
  if(c === 'dob' && o[c] === '01/01/1900') a[c] = 'N/A';
  else a[c] = o[c];
  return a;
}, {}));
console.log(result);
Nikhil Aggarwal
  • 26,884
  • 3
  • 37
  • 53
1

Another important thing to mention is that it's generally a bad idea to use for ... in construct to iterate over array items in JavaScript (see Why is using "for...in" with array iteration a bad idea? for some explanations).

shkaper
  • 3,514
  • 1
  • 15
  • 31
1

Just a single line of code by mapping the wanted properties.

var selectedColumns = ['first','last','city'],
    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 }],
    result = data.map(o => Object.assign(...selectedColumns.map(k => ({ [k]: o[k] }))));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

You will find Array.filter suits this use-case

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => {
    return word.length > 6;
});

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Matthew Spence
  • 934
  • 2
  • 9
  • 24
0

You could look into using filters where you build the filtering method based on the search criteria and return the filtered array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const newArr = oldArr.filter(record => record.first === 'Nina')
//newArr would only have Nina's record

alternatively if you are trying to go by having a particular field you can still use filter as well

var newArr2 = data.filter(record => record.hasOwnProperty('first'))
// newArr2 would have all records with the property name
tsudodog
  • 61
  • 3