首页 > 解决方案 > 如何在 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);
        }
    } 
}

但我无法将元素添加回数组(与之前的位置相同)。在添加关系元素的同时,我们还需要检查它是否已经存在。如果已经存在则无需添加。

有人可以帮我解决这个问题。

标签: angulartypescriptangular6angular5

解决方案


我会使用不可变的方法,看起来像这样:

const modified = choices.map(c => c[0] === 'relationship' ? [c[0], 'mynewvalue'] : c);

这导致:

[ 
 [ "gender", "Gender" ], 
 [ "age", "Age" ], 
 ["relationship", "mynewvalue"], 
 [ "state", "State" ] 
]

推荐阅读