【问题标题】:how to loop through an array of objects on reactjs then remove objects based on criteria [duplicate]如何遍历reactjs上的对象数组然后根据条件删除对象[重复]
【发布时间】:2021-02-06 01:40:12
【问题描述】:

我正在使用reactjs,下面有以下数据,我想遍历数组然后if key === "oneline" or key === "twoline" 删除整个对象。

在这个例子中,移除两个对象(转换)后,根据上面的描述,它只会返回数组内有03的对象。

const data = [
   {0: {key: "zeroline", door: "zero"}},
   {1: {key: "oneline", door: "one"}},
   {2: {key: "twoline", door: "two"}},
   {3: {key: "threeline", door: "three"}},
]

任何帮助都会非常有帮助。

【问题讨论】:

标签: javascript reactjs algorithm react-native ecmascript-6


【解决方案1】:

一种方法是:

const result = Object.keys(data).reduce((filtered,key,index) => {
   //Getting specific object of array
   //Example for first: data[0]["0"] === {key: "zeroline",door "zero"}
   const object = data[index][key];
   
   //Check if object key is zeroline or twoline
   if(object.key === "zeroline" || object.key === "twoline"){
     //If it is we push object to array
     filtered.push(object)
    }
   return filtered
},[])

【讨论】:

    【解决方案2】:

    使用数组过滤方法。 filter() 方法创建一个数组,其中填充了所有通过测试的数组元素。 数组过滤器的语法:array.filter(function(currentValue, index, arr), thisValue)

    const data = [
      { 0: { key: "zeroline", door: "zero" } },
      { 1: { key: "oneline", door: "one" } },
      { 2: { key: "twoline", door: "two" } },
      { 3: { key: "threeline", door: "three" } },
    ];
    
    let ret = data.filter((x, i) => x[i].key !== "oneline" && x[i].key !== "twoline");
    console.log(ret);

    【讨论】:

      【解决方案3】:

      您可以使用Array#filter 将其过滤掉。

      const keywords = ['twoline', 'oneline'], data = [{0: {key: "zeroline", door: "zero"}},{1: {key: "oneline", door: "one"}},{2: {key: "twoline", door: "two"}},{3: {key: "threeline", door: "three"}}];
      
      const res = data.filter((v, i) => keywords.indexOf(v[i].key) === -1);
      
      console.log(res);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-07
        • 1970-01-01
        • 2014-01-20
        • 2014-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-02
        相关资源
        最近更新 更多