I'm trying to cleanly grab some fields I need from an object.
The scenario is this:
I've got an object that is stored with certain 'extra' properties that exist because of the way we've set up our store in Redux. It'll look something like this:
var formData = {
account_name: 'SomeAccountName',
custom_domain_name: '',
id: 152
};
I'm trying to grab the fields I need from this object, which in this case are only popup: true
and account_name
, since custom_domain_name
is empty. I'll be adding the necessary fields as params to the end of the URL.
What I've got so far works, but seems clunky to me. I was hoping I could do something with object destructuring, such as:
var fields = ['account_name']
var necessaryFields = { ...fields } = formData
But of course that doesn't work. This is what I've got instead:
//this turns an array of field objects into just the name of the field
const fieldNames = fields.map(field => field.key);
//so here I just grab the field name if it's not an empty string
//and stick it in the new object. `popup: true` is not a required
//field, but it is necessary for the URL.
let necessaryFields = fieldNames.reduce(
(newFormObject, fieldName) => {
if (formData[fieldName]){
newFormObject[fieldName] = formData[fieldName];
}
return newFormObject;
}, { popup: true });
After this code runs, I just run the object through an existing addParamsToUrl
function (that unfortunately does not account for empty fields) that pretty much just does field_name=field_value&
with each key-value pair.
Is there a nicer way to do this? I'm also always looking to make my code as functional as possible (and that's possibly why this irks me).
1 Answer 1
I think you could do this in one go using Object.keys
on your formData
Object, followed by a few methods from the Array
and String
prototype.
var formData = {
account_name: 'SomeAccountName',
custom_domain_name: '',
id: 152
};
var enc = encodeURIComponent;
// create an array from formData props
var query = Object.keys( formData )
// filter by the prop value length
// which will only give you props where the value
// has a length property which is greater than 0.
.filter( key => formData[key].length )
// map to acctually add the value to the filtered props
// separated by equal signs.
.map( key => enc( key ) + '=' + enc( formData[key] ) )
// add your popup prop
.concat( 'popup=true' )
// join your array elements to a string separated by &.
.join( '&' )
// finally add ? to the beginning of the string.
.replace ( /^/,'?' );
// here is your query string.
console.log(query)
.as-console-wrapper { top: 0; }