Please read fully. Do not mark it duplicate until you really find it. I have an array of objects like below.
const filterParams = [
{ 'waterfront_type[]': 'Cove' },
{ 'area[]': 'Applehead Island' },
{ 'waterfront_type[]': 'Channel' },
{ 'waterfront_type[]': 'Open Water' },
{ baths: '0 - 14' },
{ price: '0.00 - 9,876,100.00' }
];
I need to loop over this and add this to form data. I'm doing like below.
filterParams.map(param => {
return formData.append(param.key, param.value);
});
Expected: param.key is waterfront_type[] and param.value is Cove. so internally it should be formData.append('waterfront_type[]', 'Cove');
Getting: both undefined. formData.append(undefined, undefined);
4 Answers 4
You can use Object.entries(), and array destructuring to get the key, and the value.
Note: the default = [] handles the case of empty objects.
filterParams.map(param => {
const [[key, value] = []] = Object.entries(param);
return formData.append(key, value);
});
If you just need to call formData(key, value), and you don't care about the returned values (if any), use Array.forEach() instead of Array.map():
filterParams.forEach(param => {
const [[key, value] = []] = Object.entries(param);
formData.append(key, value);
});
Comments
param variable passed to .map function is a javascript object and you cannot access its keys by using just object.key. Instead do:
filterParams.map(param => {
var keys = Object.keys(param);
return formData.append(keys[0], param[keys[0]]);
});
Here, we are getting all the keys of the param object and get the first (0th index) as the key you require (assuming that your array have objects with one key).
Comments
So you want to put all dictionary entrySet into a FormData:
filterParams.forEach(param => {
Object.keys(param).forEach(function(key) {
let value = param[key];
formData.append(key, value);
});
});
It will produce the output of:
["waterfront_type%5B%5D=Cove",
"area%5B%5D=Applehead%20Island",
"waterfront_type%5B%5D=Channel",
"waterfront_type%5B%5D=Open%20Water",
"baths=0%20-%2014",
"price=0.00%20-%209%2C876%2C100.00"]
Comments
you can use javascript filters
filterParams = filterParams.filter(function(itm){
Object.keys(itm).forEach(function(key, value){
return formData.append(key, value);
})
})
8 Comments
.filter if all you want is to loop through the array?.filter, .map, .forEach, .some, .every, .find? There would surely need to be a single one if they just go through the array..filter. Why? What's the advantage over any other method? And are you aware of why are there different ones?
Expected: param.key is waterfront_type[]why would you expect that?.mapat all, if all you want is to loop through the array?