从数组中删除对象,具有与正则表达式模式匹配的值的对象

时间:2018-06-06 14:26:10

标签: javascript regex

我有一个下面给出的javascript数组,我试图删除与父元素匹配级别模式的对象。例如,如果类型是父级,级别是1-2,那么我想删除级别为1-2-1,1-2-2,1-2-3的子项

var arr = [{
    type: "parent",
    Level: "1-1",
  },
  {
    type: "parent",
    Level: "1-2",
  },
  {
    type: "child",
    Level: "1-2-1",
  },
  {
    type: "child",
    Level: "1-2-2",
  },
  {
    type: "child",
    Level: "1-2-3",
  } {
    type: "parent",
    Level: "1-3",
  }
];

我正在尝试使用正则表达式来完成它,但现在却无法真正做到。有人可以帮帮我吗?或者,如果有任何可以使用的lodash方法?

更新

这是我到目前为止尝试的内容,我知道它不使用正则表达式,但可能它可以做我想要的。

var parentLevel = "1-2" + "-";
var length = arr.length;
for (var k = 0; k < length; k++) {
  if (arr[k].Level.startsWith(parentLevel)) {
    arr.splice(k, 1);
  }
}

3 个答案:

答案 0 :(得分:1)

您可以使用Array.filter来实现这一目标。

var arr = [{
    type: "parent",
    Level: "1-1",
  },{
    type: "parent",
    Level: "1-2",
  },{
    type: "child",
    Level: "1-2-1",
  },{
    type: "child",
    Level: "1-2-2",
  },{
    type: "child",
    Level: "1-2-3",
  },{
    type: "child",
    Level: "1-4-3",
  },{
    type: "parent",
    Level: "1-3",
  }
];

var nodetoberemoved = "1-2";
var result = arr.filter(function(elem){
        return !elem.Level.indexOf(nodetoberemoved+"-")==0;
});

console.log(result)

答案 1 :(得分:0)

removeChildren("1-2", arr)

removeChildren = (parent, arr) => {
  const regex = new RegExp("^" + parent + "-[0-9]+$")
  return arr.filter(a => !regex.test(a.Level))
}

注意:请记住,这只会删除直接孩子。如果要删除所有子子,请使用new RegExp("^" + parent + "[\-0-9]+$")

答案 2 :(得分:0)

我认为这是您想要的动态解决方案。

var arr = [{
    type: "parent",
    Level: "1-1",
  },{
    type: "parent",
    Level: "1-2",
  },{
    type: "child",
    Level: "1-2-1",
  },{
    type: "child",
    Level: "1-2-2",
  },{
    type: "child",
    Level: "1-2-3",
  },{
    type: "child",
    Level: "1-4-3",
  },{
    type: "parent",
    Level: "1-3",
  }
];

//Separate the parents and children into two arrays so we can loop through them.
var parents = arr.filter(elem => elem.type === 'parent')    
var children = arr.filter(elem => elem.type === 'child')

//Loop over arrays to remove children from the variable arr
parents.forEach(parent => {
    // Dynamically build a regex to filter out the children
    var regEx = new RegExp("^" + parent.Level + "-");

    children.forEach(child => {
        //if child matches a parent level it will be removed from the original arr variable
        if(regEx.test(child.Level)){
            arr.splice(arr.indexOf(child, 0),1)
        }
    })
})