过滤嵌套对象的数组

时间:2016-03-20 01:20:39

标签: javascript filter angular

我试图在Angular2中创建一个过滤管道,它必须过滤包含多个嵌套对象的数组。这些对象来自Salesforce,有时会包含嵌套对象,如下例所示:

Object {
    Id: "a0436000001awB5AAI",
    Name: "Some product",
    Store__c: "a0436000001awC2JJU",
    Product__c: "a0136000001UGzzAAG",
    Product__r: Object {
        Id: "a0136000001UGzzAAG",
        Name: "Parent product",
        ...
    },
    ...
}

正常的排序方法不能很好地工作,因为它们往往不会达到多个级别。我一直在努力写自己的,但我似乎无法弄明白。这就是我现在所拥有的:

// # Filter Array of Objects
@Pipe({ name: 'filter' })
export class FilterArrayPipe implements PipeTransform {

    transform(value, args) {

        let filterKeys: string[];
        if (args[1]) {
            let parts = args[1].replace(' ', '').split(',');
            filterKeys = parts;
        }

        if (!args[0]) {

            return value;

        } else if (value) {

            return value.filter(item => {

                for (let key in item) {

                    if ((typeof item[key] === 'string' || item[key] instanceof String && item[key]) && (item[key].indexOf(args[0]) !== -1)) {

                        if (filterKeys && filterKeys.length > 0) {

                            if (item[key] in filterKeys) {

                                return true;

                            }
                        }
                        else {

                            return true;

                        }
                    }

                }
            });
        }
    }

}

现在它根本不起作用。

2 个答案:

答案 0 :(得分:1)

使代码工作所需的只是更改行:

img {
outline: 1px solid white;
outline-offset: -4px;
}

运营商'用于检查对象上是否存在属性。

相反,对于您使用的数组:

if (item[key] in filterKeys) {

这是一个有效的plunker

答案 1 :(得分:0)

我明白了。它并不完美,但它确实起到了作用:

libc::dup()

基本上只需将对象展平,然后对其进行过滤。

相关问题