简体   繁体   English

数组中的javascript过滤器数组

[英]javascript filter array in array

I have the following code based on docs我有以下基于文档的代码

var arr = [
  { id: 15 },
  { x: [{ id: 777 }, { id: 'xx' }, { notidproperty: 987 }]},
  { id: 1111 }
];

function filterByID(obj) {
  if ('id' in obj && typeof(obj.id) === 'number' && !isNaN(obj.id)) {
    return true;
  } else if (Object.prototype.toString.call(obj) === '[object Array]') { //obj type is Object, not Array
    obj.filter(filterByID);
  } else {
    return false;
  }
}

var arrByID = arr.filter(filterByID);
console.log('expected length = 3, actual length = ' + arrByID.length);
console.log(arrByID);

How can I filter 'arr' array ?如何过滤“arr”数组? Is there any other techniques to get proper result?有没有其他技术可以获得正确的结果?

EDIT: the expected result is filtered array of objects that have id property with numeric value编辑:预期结果是过滤的对象数组,这些对象具有带数值的 id 属性

So expected Id values are 15, 777, 1111所以预期的 Id 值为 15, 777, 1111

I suggest to use Array#reduce() instead of Array#filter() , because you need a flat array for the result, to count.我建议使用Array#reduce()而不是Array#filter() ,因为您需要一个平面数组来计算结果。

I use isFinite as check for the id .我使用isFinite作为检查id

 function rr(r, a) { Object.keys(a).forEach(function (k) { if (Array.isArray(a[k])) { r = r.concat(a[k].reduce(rr, [])); } else { isFinite(a.id) && r.push(a); } }); return r; } var arr = [{ id: 15 }, { x: [{ id: 777 }, { id: 'xx' }, { notidproperty: 987 }] }, { id: 1111 }], result = arr.reduce(rr, []); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Almost there.差不多好了。 In the else if you don't return anything.else if您不返回任何内容。 Instead of代替

obj.filter(filterByID);

try return (obj.filter(filterByID).length > 0);尝试return (obj.filter(filterByID).length > 0);

because if the result of the recursive filterByID is an array with length more than 0, you want to add that to the outer result.因为如果递归 filterByID 的结果是一个长度大于 0 的数组,您希望将其添加到外部结果中。

You have to modify the following branch:您必须修改以下分支:

if (Object.prototype.toString.call(obj) === '[object Array]') { //obj type is Object, not Array
  obj.filter(filterByID);
}

This only filters but returns no result.这仅过滤但不返回结果。 And your object with x property of Array type will not be processed here.并且这里不会处理具有 Array 类型的 x 属性的对象。 So:所以:

if(obj.x && Array.isArray(obj.x)){
  return obj.x.filter(filterByID).length>0
}

Or:或者:

if(obj.x && Array.isArray(obj.x)){
  obj.x = obj.x.filter(filterByID)
  return true
}

(Depending on what you want to do) (取决于你想做什么)

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

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