我有一个包含所选项目的更改数组,其中key是id:
[1, 2, 4, 6]
对象数组:
items = [
{
id: 1,
selected: false
},
{
id: 2,
selected: false
},
{
id: 3,
selected: false
},
{
id: 4,
selected: false
},
{
id: 5,
selected: true
},
{
id: 6,
selected: false
}
]
如何将所选数组映射到项目并更改'已选择'为true而其他项目将其更改为false?
答案 0 :(得分:3)
items.forEach(item => item.selected = array.contains(item.id))
只需遍历项目,根据数组中是否包含id来设置所选属性。
答案 1 :(得分:2)
var items = [
{
id: 1,
selected: false
},
{
id: 2,
selected: false
},
{
id: 3,
selected: false
},
{
id: 4,
selected: false
},
{
id: 5,
selected: true
},
{
id: 6,
selected: false
}
];
var array = [1, 2, 4, 6];
items.forEach(function(item) {
item.selected = (array.indexOf(item.id) !== -1);
})
答案 2 :(得分:1)
您可以使用Map
并迭代数组并设置所有true
,然后选择var selected = [1, 2, 4, 6],
items = [{ id: 1, selected: false }, { id: 2, selected: false }, { id: 3, selected: false }, { id: 4, selected: false }, { id: 5, selected: true }, { id: 6, selected: false }],
map = new Map;
items.forEach(a => (map.set(a.id, a), a.selected = false));
selected.forEach(a => map.get(a).selected = true);
console.log(items);
。
.as-console-wrapper { max-height: 100% !important; top: 0; }
var selected = [1, 2, 4, 6],
items = [{ id: 1, selected: false }, { id: 2, selected: false }, { id: 3, selected: false }, { id: 4, selected: false }, { id: 5, selected: true }, { id: 6, selected: false }],
set = new Set(selected);
items.forEach(a => a.selected = set.has(a.id));
console.log(items);
Set
的版本。
.as-console-wrapper { max-height: 100% !important; top: 0; }
qx.ui.form.AbstractField
答案 3 :(得分:0)
var arr = [1,2,4,6];
var items = [
{
id: 1,
selected: false
},
{
id: 2,
selected: false
},
{
id: 3,
selected: false
},
{
id: 4,
selected: false
},
{
id: 5,
selected: true
},
{
id: 6,
selected: false
}
];
var notSelected = $.grep(items, function(e) { return arr.indexOf(e.id) == -1 }).map(function(e) { e.selected = false; return e;});
var selected = $.grep(items, function(e) { return arr.indexOf(e.id) != -1 }).map(function(e) { e.selected = true; return e;});
结果:
notSelected.concat(selected);
答案 4 :(得分:-1)
请尝试一下。我认为它会起作用......
$new=array();
foreach($items as $item){
if($item['selected']==false){
$new.=array_merge($item['id']);
}
}
print_r($new);
并将非选定项目更改为true。
foreach($items as $item){
if($item['selected']==false){
$item['selected']=true;
}
}