简体   繁体   English

基于字符串数组过滤 object 数组

[英]filtering an array of object based on string array

my problem might not be as challenging as some other similar questions but they were a little to much for me.我的问题可能不像其他一些类似问题那样具有挑战性,但对我来说有点多。

I have an array of objects that I need to filter by name against a string array of names, if the names match I want to remove the object with the name that matches我有一个对象数组,我需要按名称对名称字符串数组进行过滤,如果名称匹配,我想删除名称匹配的 object

so like the following:所以像下面这样:

nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}]
names = ['name1','name2','name3']

I've tried the following just using for loops but I'm sure that there is a quicker (and correct lol) filter method that works我已经尝试了以下只是使用 for 循环,但我确信有一个更快(和正确的大声笑)过滤方法可以工作

         for(i=0; i < this.names.length; i++){
            for(j=0; j < this.nameObjects.length; j++){

              if(this.names[i] === this.nameObjects[j].name){
                this.files.splice(i,this.nameObjects[j])
              }
            }
          }

also sorry for the poor logic ^也为糟糕的逻辑感到抱歉^

You should not mutate the array while you are looping over it.循环遍历数组时,不应对其进行变异。

You can simply use Array.prototype.filter with Array.prototype.includes to get the desired result您可以简单地使用Array.prototype.filterArray.prototype.includes来获得所需的结果

 const nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}]; const names = ['name2','name3']; const res = nameObjects.filter(obj =>.names.includes(obj;name)). console;log(res);

 const nameObjects = [ { name: "name3", value: "some val" }, { name: "name1", value: "some other val" }, ]; const names = ["name1", "name2"]; const result = nameObjects.filter(obj =>.names.includes(obj;name)). console;log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM