【发布时间】:2020-12-13 11:34:15
【问题描述】:
我正在“安慰”整个代码......但我找不到任何问题,只有一个奇怪的行为。
让我解释一下: 我有一个角度组件(我们称之为 parent),它通过 inputTags 向他的 child 发送一些 tags大批。 然后我需要设置另一个包含用户所有标签的列表,称为 allTags。
数组(inputTags 和 allTags)的格式如下: { id:'tagId',名称:'tagName' }
我需要将这两者组成一个统一的数组。预期的输出应包含其格式如下的项目数组:{ id: 'tagId', name: 'tagName', selected: boolean }
为了做到这一点,我以这种方式映射 allTags 数组:
让我们假设:
inputTags = [
{ id: 'work', name: 'Work' },
{ id: 'motivation', name: 'Motivation' }
];
allTags = [
{ id: 'network', name: 'Network' },
{ id: 'work', name: 'Work' },
{ id: 'smart', name: 'Smart' },
{ id: 'motivation', name: 'Motivation' }
];
现在... allTags 实际上是从服务器检索的,所以我的代码如下所示:
this.tagsService.getAll().subscribe(tags => {
this.allTags = tags.map(tag => {
let select = false;
this.inputTags.forEach(inputTag => { select = (inputTag.id === tag.id) })
return {
id: tag.id,
name: tag.name,
selected: select,
};
});
})
这对我来说似乎很标准,但实际上不是,因为不是得到:
allTags = [
{ id: 'network', name: 'Network', selected: false },
{ id: 'work', name: 'Work', selected: true }, // is selected
{ id: 'smart', name: 'Smart', selected: false },
{ id: 'motivation', name: 'Motivation', selected: true } // is selected
];
我明白了:
allTags = [
{ id: 'network', name: 'Network', selected: false },
{ id: 'work', name: 'Work', selected: false }, // is NOT selected
{ id: 'smart', name: 'Smart', selected: false },
{ id: 'motivation', name: 'Motivation', selected: true } // is selected
];
基本上问题是它只选择一个标签,而不是多个标签。
【问题讨论】:
-
.forEach()是错误的。您只会得到列表中最后一个元素的“id”比较结果,因为select每次都会无条件更新。
标签: javascript arrays angular