繁体   English   中英

如何返回属性与数组匹配的对象数组?

[英]How can I return an array of objects whose property matches an array?

我有一个像

array = [
  { name: "john", tag: ["tag1", "tag2"] },
  { name: "doe", tag: ["tag2"] },
  { name: "jane", tag: ["tag2", "tag3"] }
];

我想获得一个包含“ tag2”和“ tag3”的对象的新数组,但不仅包含“ tag2”或“ tag1”和“ tag2”。

结果应为:

newArray = [{ name: "jane", tag: ["tag2", "tag3"] }];

我尝试使用以下过程来做到这一点:

tags = ["tag2", "tag3"];
newArray = [];
tags.forEach(t => {
  array.forEach(data => {
    data.tag.forEach(item => {
      if (item === t) {
        newArray.push(data);
      }
    });
  });
});

但是我得到了所有物品。

如果我对您的理解正确,则希望搜索顶级数组,以查找其tag属性是与['tag2', 'tag3']完全匹配的数组的所有项目。

您可以通过根据上述条件过滤数组来实现。

这是一种方法:

 const array = [ { name: 'john', tag: ['tag1', 'tag2'] }, { name: 'doe', tag: ['tag2'] }, { name: 'jane', tag: ['tag2', 'tag3'] } ]; const tagsToMatchOn = ['tag2', 'tag3']; // find all elements who's tag property exactly matches // the above tags (in presence, not necessarily in order) const newArray = array.filter(item => ( item.tag.length === tagsToMatchOn.length && tagsToMatchOn.every(t => item.tag.includes(t)) )); console.log(newArray); 

如果相反,您想查找其tag属性是一个包含['tag2', 'tag3' ]所有但也可以包含其他标签的数组的所有项目,则可以尝试如下操作:

 const array = [ { name: 'john', tag: ['tag1', 'tag2'] }, { name: 'doe', tag: ['tag2'] }, { name: 'jane', tag: ['tag2', 'tag3'] } ]; const tagsToMatchOn = ['tag2', 'tag3']; // find all elements who's tag property includes // all of the above tags but can also contain others const newArray = array.filter(item => tagsToMatchOn.every(t => item.tag.includes(t)) ); console.log(newArray); 

这可能不是最优雅的解决方案,但它确实会返回您想要的内容。

array = [{name:'john',
          tag: ['tag1','tag2'] 
         },
         {name:'doe',
          tag: ['tag2'] 
         },
         {name:'jane',
          tag: ['tag2','tag3'] 
         }
        ];

const newArray = [];
for (let index = 0; index < array.length; index++) {
    if(array[index].tag[0] === 'tag2' && array[index].tag[1] === 'tag3') {
        newArray.push(array[index])
    }
}

或者,如果您想更多地使用es6:

array.forEach(element => {
  if(element.tag[0] === 'tag2' && element.tag[1] === 'tag3') {
    newArray.push(element)
  }
});

你可以这样

借助过滤器每一个

基本上,我在这里要做的是首先要遍历arr的每个元素(使用过滤器)。 通过使用我正在检查的每一项,元素的tag属性是否包含我们需要的所有标签。 如果超过,则将其包含在最终输出中;否则,我们将其包含在最终输出中

 let arr = [{name:'john', tag: ['tag1','tag2'] }, {name:'doe', tag: ['tag2'] }, {name:'jane', tag: ['tag2','tag3'] } ]; let tags = ['tag2','tag3']; let op = arr.filter(e=> tags.every(el=> e.tag.includes(el))); console.log(op); 

暂无
暂无

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

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