0

I have the following script. As you can see item.value and item.name are differently. Can I write this more dynamically, easily in javascript?

setOptions(id, selection) {
    var options = ''
    var newArray = []

    if (selection == 'settings') {
         options = this.getStatuses(id);
         newArray = options.map(item => { return { id: item.id, text: item.value } });
    } else if (selection == 'route' && id == 'profiles') {
         options = this.getProfiles;
         newArray = options.map(item => { return { id: item.id, text: item.name } });
    }
    return newArray
}
nhatimme
  • 383
  • 3
  • 19
  • You can do destructuring and inside the return function you map the array – MK. Jun 05 '21 at 09:18
  • You can use a variable with either `"value"` or `"name"` and dynamic property access (`item[propName]`), like this: `const newArray = options.map(item => ( { id: item.id, text: item[propName] } ));` – T.J. Crowder Jun 05 '21 at 09:20
  • Side note: In new code, don't use `var`, use `let` or `const`. And there's no reason to assign a value to a variable (the initializers you have on `options` and `newArray`) when you're just going to overwrite it with a different value a moment later without using it in the meantime. – T.J. Crowder Jun 05 '21 at 09:21
  • @T.J.Crowder can you provide me an example in total? – nhatimme Jun 05 '21 at 09:23
  • See https://pastebin.com/GSr5YXfF – T.J. Crowder Jun 05 '21 at 09:24
  • var contacts = [{ "ContactId" : "1", "ContactName" : "Bob" },{ "ContactId" : "2", "ContactName" : "Ted" }]; var sites = [{ "SiteId" : "1", "Location" : "MN" },{ "SiteId" : "2", "Location" : "FL" }]; function convertResponse(response, text, value) { return $.map(response, function(it) { return { value: it[value], text: it[text] }; }); } var convertedContacts = convertResponse(contacts, 'ContactId', 'ContactName'); var convertedSites = convertResponse(sites, 'SiteId', 'Location'); – Puneet Goel Jun 05 '21 at 09:27
  • @T.J.Crowder works perfect. Thanks! – nhatimme Jun 05 '21 at 09:29

0 Answers0