是否有更好的方法根据特定属性的一组可能值来过滤对象数组?
这有效,但似乎有点笨拙。
const all = [
{id: 1}, {id: 2}, {id: 3} ...
]
const ids = [2, 3];
const selected = (all, ids) =>
all.filter(obj => ids.map(id => id === obj.id).some(match => match));
selected(all, ids);
// [{id: 2}, {id: 3}]
在Python中会是这样的:
selected = [obj for obj in all if obj.id in ids]
答案 0 :(得分:2)
您可以简单地使用Array.filter()
和Array.includes()
过滤掉数组:
const all = [ {id: 1}, {id: 2}, {id: 3} ];
const ids = [2, 3];
const selected = (all, ids) => all.filter(obj => ids.includes(obj.id));
console.log(selected(all,ids));
答案 1 :(得分:2)
您可以使用Array.filter
,object destructuration
和Array.includes
,例如:
const all = [{
id: 1,
}, {
id: 2,
}, {
id: 3,
}];
const ids = [
2,
3,
];
const selected = (all, ids) => all.filter(({
id,
}) => ids.includes(id));
console.log(selected(all, ids));
// [{id: 2}, {id: 3}]
答案 2 :(得分:0)
您可以将Set
用作通缉的<select name="displayId" class="form-control" id="areaSelect">
<option value="" disabled selected>Select one...</option>
<?php foreach($displayLocation as $displayLoc): ?>
<optgroup label="<?php echo $displayLoc['location_name']?>">
<option value="<?php echo $displayLoc['displayID']?>"><?php echo $displayLoc['display_name']?></option>
<?php endforeach?>
</select>
,然后针对过滤条件进行检查。
id