angular - 如何在 Typescript 中的数组的特定位置附加数据
问题描述
我从后端获取这些数据。
"choices": [ [ "gender", "Gender" ], [ "age", "Age" ], ["relationship", "Relationship Type"], [ "state", "State" ] ]
还有另一个值也来自后端,即compareValue = "users"/"group"
compareValue 可以是“用户”或“组”。
基于 compareValue,我们需要操作“choices”数组。当 compareValue 等于 group 时,我们需要删除“relationship”元素,当 compareValue 等于 users 时,我们需要在数组的相同位置添加回“relationship”。
我已经写了下面的逻辑来删除元素,它工作正常。我能够成功删除关系元素。
if (compareValue == "group") {
for (var i=choices.length; i--; ) {
if (choices[i][0] === 'relationship'){
choices.splice(i, 1);
}
}
}
但我无法将元素添加回数组(与之前的位置相同)。在添加关系元素的同时,我们还需要检查它是否已经存在。如果已经存在则无需添加。
有人可以帮我解决这个问题。
解决方案
我会使用不可变的方法,看起来像这样:
const modified = choices.map(c => c[0] === 'relationship' ? [c[0], 'mynewvalue'] : c);
这导致:
[
[ "gender", "Gender" ],
[ "age", "Age" ],
["relationship", "mynewvalue"],
[ "state", "State" ]
]
推荐阅读
- jmeter - 仅使用一个凭证进行负载测试
- html - 使输入和跨度彼此相邻
- java - 删除所有点,但不删除 \in 数字 - Java
- json - 在问题之间共享数据——不能为第二个业务产生不同的结果
- c# - 我想要它,所以当我单击下拉选项并单击文本时,图像旁边会出现一个图像
- javascript - 检查经纬度列表是否在范围内
- python - Airflow - 使用 COPY 导出 PostgreSQL 表
- react-native - 如何仅渲染数组中的第一个对象?React Native 扁平列表
- python - 简化 Python 中的条件语句
- python - Python嵌套for循环排序