【问题标题】:How to append data at a particular position of an Array in Typescript如何在 Typescript 中的数组的特定位置附加数据
【发布时间】:2021-06-07 14:44:59
【问题描述】:

我正在从后端获取这些数据。

"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);
        }
    } 
}

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

谁能帮我解决这个问题。

【问题讨论】:

    标签: angular typescript angular6 angular5


    【解决方案1】:

    我认为保留原始数组并根据compareValue 的当前值创建它的过滤版本比从数组中删除并添加回该数组更有意义。

    如果compareValue"users",那么我们保留包括"relationship" 在内的所有元素。如果compareValue"group",那么我们将返回除"relationship" 之外的所有内容。

    const filteredChoices = choices.filter(choice => 
      compareValue === "users" || choice[0] !== "relationship"
    );
    
    

    【讨论】:

      【解决方案2】:

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

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

      结果:

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

      【讨论】:

      • 这里能不能加个过滤条件,比如判断关系是否不存在,那么就追加吧。
      • 我不明白预期的输出是什么。你能提供具体的例子吗?如果我只有“它不工作”,我很难更新答案。你的意思是:如果数组不包含键为“relationship”的项目我想添加一个新的对wir [“relationship”,“newvalue”] ?
      猜你喜欢
      • 2021-11-01
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 2018-05-24
      • 2019-05-24
      • 1970-01-01
      • 2020-07-07
      • 2022-11-21
      相关资源
      最近更新 更多