[英]how to loop over array of objects and get values
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. 预期:param.key是waterfront_type [],param.value是Cove。 so internally it should be
formData.append('waterfront_type[]', 'Cove');
因此在内部应为
formData.append('waterfront_type[]', 'Cove');
Getting: both undefined. 获取:两者均未定义。
formData.append(undefined, undefined);
You can use Object.entries()
, and array destructuring to get the key, and the value. 您可以使用
Object.entries()
和数组解构来获取键和值。
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()
: 如果只需要调用
formData(key, value)
,而不关心返回的值(如果有),请使用Array.forEach()
而不是Array.map()
:
filterParams.forEach(param => {
const [[key, value] = []] = Object.entries(param);
formData.append(key, value);
});
param
variable passed to .map
function is a javascript object and you cannot access its keys by using just object.key
. 传递给
.map
函数的param
变量是一个javascript对象,您不能仅使用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). 在这里,我们获取了
param
对象的所有键,并获得了第一个(第0个索引)作为所需的键(假设数组中的对象具有一个键)。
So you want to put all dictionary entrySet into a FormData: 因此,您要将所有字典entrySet放入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"]
you can use javascript filters 您可以使用javascript过滤器
filterParams = filterParams.filter(function(itm){
Object.keys(itm).forEach(function(key, value){
return formData.append(key, value);
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.