[英]Why is the following map function returning the strings with commas?
我正在遍历一个对象。 如果它的按键彼此的值相匹配fields
对象则返回值type
的该fields
的对象:
// OBJECTS
user: {
email: '',
password: ''
}
formFields: [
{ name: 'email', type: 'text', required: true },
{ name: 'password', type: 'password', required: true }
]
// HTML
<input :type="getPropType($key)"
// FUNCTION
getPropType (key) {
console.log(this.fields)
console.log(key)
return this.fields.map(field => {
if (field.name === key) return field.type
})
}
它的工作原理是,每个field.type
都返回逗号。
这很奇怪,因为日志不输出任何逗号:
可能是什么原因?
我认为您要尝试的是提取名称与键值相同的对象的type
,在这种情况下,一种更合适的解决方案是准确地做到这一点-即找到具有给定名称的元素,然后提取其类型
getPropType(key) {
console.log(this.fields)
console.log(key);
var type;
this.fields.some(field => {
if (field.name === key) {
type = field.type;
return true;
}
});
return type
}
如果要使用.map()
,则
return this.fields.filter(field => field.name === key).map(field => field.type).join('')
Array.prototype.map()返回数组。 您的“ getPropType”返回了[“ text”,“”],在您的情况下应该减少它。
return this.fields.map(field => {
if (field.name === key) return field.type
}).reduce(function(prev, curr, index, array){return prev + curr});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.