[英]Filtering an array of nested objects
我试图在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;
}
}
}
});
}
}
}
目前,它根本不起作用。
使代码正常工作所需要做的就是更改以下行:
if (item[key] in filterKeys) {
“ in运算符”用于检查对象上是否存在属性。
相反,对于数组,请使用:
if (filterKeys.indexOf(key) > -1) {
这是一个工作的家伙
我想到了。 它不是完美的,但是可以做到:
private flattenObject(ob) {
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object') {
var flatObject = this.flattenObject(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
transform(value, args) {
let filterKeys: string[];
if (args[1]) {
console.log(args[1]);
if (typeof args[1] === 'string') {
console.log('string');
let parts = args[1].replace(' ', '').split(',');
filterKeys = parts;
} else if (typeof args[1] === 'object') {
console.log('object');
filterKeys = args[1];
}
}
if (!args[0]) {
return value;
} else if (value) {
let retArr: Object[] = [];
for (let obj of value) {
let filterable: Object = this.flattenObject(obj);
for (let key in filterable) {
key = String(key);
let val = String(filterable[key]);
if (val.indexOf(args[0]) !== -1) {
if (filterKeys && filterKeys.length > 0) {
if (filterKeys.indexOf(key) > -1) {
retArr.push(obj);
}
}
else {
return true;
}
}
}
}
return retArr;
}
}
基本上只是将对象展平,然后对其进行过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.