在 javascript 中,我有这种情况:
this.props.number
始终是数字 0、1 或 2
this.props.columnas
是这样的对象数组:
[
{value:'1',text:'AA'},
{value:'2',text:'BB'},
{value:'3',text:'CC'},
{value:'4',text:'DD'},
{value:'5',text:'EE'},
{value:'6',text:'FF'},
{value:'7',text:'GG'}
]
selected
也是这样的对象数组:
[{col:"2", ope:"", val:""}, {col:"5", ope:"", val:""}, {col:"7", ope:"", val:""}, ]
我有这段代码:
this.props.columnas.map(function(col){
if(this.props.number == 0) {
if (col.value == selected[0].col)
disabledIndice = true
else
disabledIndice = false;
}
else if(this.props.number == 1) {
if (col.value == selected[0].col || col.value == selected[1].col)
disabledIndice = true
else
disabledIndice = false;
}
else if(this.props.number == 2) {
if (col.value == selected[0].col || col.value == selected[1].col || col.value == selected[2].col)
disabledIndice = true
else
disabledIndice = false;
}
return <option value={col.value} disabled={disabledIndice}>{col.text}</option>
}.bind(this))}
(忘记 bind
. function
和 es5,无论如何我都会使用箭头函数)
它太长了,它没有做我需要做的事情。我想在 selected
中再次使用 map 找到哪个 col.value
与存储在 selected
上的相同.
在上面的代码中,我假设我将有 3 个对象用于 selected
,但情况并非总是如此。有时可能是 1、2 或 3 个对象,即 s why the code is using those ìf
对于每种情况(对象的数量由 this.props.number
定义)。太丑了。
我试过这样的:
this.props.columnas.map(function(col){
indicesYaSeleccionado.map(function(item){
if (col.value == item.col)
disabledIndice = true
else disabledIndice = false;
});
return <option key={constant.guid()} value={col.value} disabled={disabledIndice}>{col.text}</option>
}.bind(this))
但我总是会得到 disabled
因为我正在比较每个值,所以我需要设置为 disabledIndice = true
至少有 1 个巧合。
有什么建议吗?解释很长,抱歉。
最佳答案
据我了解,您只需查看当前 col
值是否在 selected.val
数组中。
this.props.columnas.map(function(col){
let disabledIndice =
selected.findIndex(e => e.col === col.value) !== -1
? true : false
return <option value={col.value} disabled={disabledIndice}>{col.text}</option>
}.bind(this))}
这段代码应该可以正常工作。
关于javascript - 映射数组并比较至少一个巧合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42514558/