如果属性与数组中的值匹配,则过滤对象

时间:2018-12-05 08:02:45

标签: javascript arrays object angular6

我有一个看起来像这样的对象:

const faultGroup = 
[{
  comments:"",
  faults:
   [{
     id:31,
     name: "speaker"
    },
    {
     id:22
     name: "earphones"
    },
    {
     id:25
     name: "keyboard"
    }];
}];

我有一个包含ID数组的数组

idArray = [25,22];

预期结果:

result = ["earphones", "keyboard"];

当前解决方案:

result = [];
faultGroup.map(fg => {
  if (!!fg.faults) {
     fg.faults.forEach(fault => {
         for (let i = 0; i < idArray.length; i++) {
            if (idArray[i] === fault.id) {
                this.result.push(fault.name);
            }
         }
     });
   }
});

我可以知道最有效的方法吗? (不确定这种情况下如何使用过滤器和包含方法)当前,我正在使用map和double for循环的组合。感谢您的帮助!

6 个答案:

答案 0 :(得分:3)

您可以reduce遍历faultGroup数组,从每个项目中提取faults数组并对其进行迭代,如果id被包含在{ {1}}:

idArray

答案 1 :(得分:1)

这也可以。

let result = [];

faultGroup.forEach(({ faults }) => {
  faults
    .filter(({ id }) => idArray.indexOf(id) > -1)
    .forEach(fault => result.push(fault));
});

答案 2 :(得分:1)

在即将到来的Array#flatMap中,您可以通过获取所需项目在单个循环中使用具有展平功能的映射。

const
    faultGroup = [{ comments: "", faults: [{ id: 31, name: "speaker" }, { id: 22, name: "earphones" }, { id: 25, name: "keyboard" }] }],
    idArray = [25, 22],
    result = faultGroup.flatMap(({ faults }) => faults
        .filter(({ id }) => idArray.includes(id))
        .map(({ name }) => name)
    );
  
console.log(result);

答案 3 :(得分:1)

var faultGroup = 
[{
  comments:"",
  faults:
   [{
     id:31,
     name: "speaker"
    },
    {
     id:22,
     name: "earphones"
    },
    {
     id:25,
     name: "keyboard"
    }]
}];
idArray = [25,22];

var res = faultGroup.map( f => f["faults"].filter( a => idArray.indexOf(a.id) > -1 ).map( r => r.name ) );

console.log(res);

答案 4 :(得分:1)

您可以使用Array.reduceArray.filterArray.includes来获得结果:

const data = [{ comments: "", faults: [{ id: 31, name: "speaker" }, { id: 22, name: "earphones" }, { id: 25, name: "keyboard" } ] }]
const ids = [25,22];

const result = data.reduce((r,{faults}) => 
  [...r, ...faults.filter(({id}) => ids.includes(id)).map(x => x.name)], [])

console.log(result)

想法是从减少开始,因为您将要更改最终结果表单,并且需要一个累加器。然后,在内部仅根据ID是否包含其元素来过滤主数组,并将结果散布到累加器内。

答案 5 :(得分:1)

JSON.parseJSON.stringify可用于检查所有键值对:

var result = [], idArray = [25,22], faultGroup = [{ comments:"", faults: [
{ id:31, name: "speaker" }, { id:22, name: "earphones" }, { id:25, name: "keyboard" }] }];

JSON.stringify(faultGroup, (k, v) => idArray.includes(v.id) ? result.push(v.name) : v);

console.log( result );