Reputation: 1721
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);
Upvotes: 0
Views: 1724
Reputation: 191946
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);
});
Upvotes: 4
Reputation: 98
you can use javascript filters
filterParams = filterParams.filter(function(itm){
Object.keys(itm).forEach(function(key, value){
return formData.append(key, value);
})
})
Upvotes: -1
Reputation: 11600
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"]
Upvotes: 0
Reputation: 3570
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).
Upvotes: 0