Return objects Using Array.from and Fat Arrow

After getting all of the selected radio buttons on my form and then converting the array like object into an array using the following code

var selectedRadios = document.querySelectorAll('input[type="radio"]:checked') 
var radios = Array.from(selectedRadios);   

I realized that the array contains input elements. What I would like to do instead is return objects containing just the id, name, and value of the input elements instead of the input elements using Array.from and fat arrow. For instance I would like to do some thing like the following

var radios = Array.from(selectedRadios, radio => new 
 {,, value:radio.value});   

what you’re trying to do is an Array Map Function.

You’re on the right lines with your code there, you just need to change the body of your arrow function.

First of all, you don’t need the new keyword when creating object literals. Also, if you want to implicitly return an object literal from an arrow function you need to wrap it in parentheses, or the interpreter will think the curly braces are opening and closing the function body and you’ll get an error.

const radios = Array.from(selectedRadios, radio => ({,, value:radio.value}));

As you’re already using ES2015 features here, you could also write your code like this:

const radios = Array.from(selectedRadios, ({ id, name, value }) => ({ id, name, value }));

This uses object destructuring for the argument passed to the arrow function, pulling out only the properties of the object that we’re interested in and making them available to the function as individual variables. It also uses the object literal shorthand, to create keys on the object using the names of the variables themselves.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.