内联JavaScript过滤器,可返回子对象

我试图在对象数组上调用filter方法,但是我不想返回整个对象。我只想返回对象的一部分。

[
   {val: 0, val2: 'a'},
   {val: 1, val2: 'b'},
   {val: 2, val2: 'c'},
   {val: 3, val2: 'd'}
].filter( obj => {
    if (obj.val > 1){
        return obj.val2
}})

该过滤器函数返回

[ { val: 2, val2: 'c' }, { val: 3, val2: 'd' } ]

但应该回来

[ { val2: 'c' }, { val2: 'd' } ]

The problem with using map is that I don't want undefined being injected into the array

评论
下载中....
下载中....

You need map() as well:

var res = [
   {val: 0, val2: 'a'},
   {val: 1, val2: 'b'},
   {val: 2, val2: 'c'},
   {val: 3, val2: 'd'}
].filter( obj => {
    if (obj.val > 1){
        return obj.val2
}}).map(i => ({val2:i.val2}));
console.log(res);
点赞
评论
燕晓彤
燕晓彤

您可以结合使用地图和过滤器。

dataArray.filter(obj => obj.val > 1 && obj.val2).map(obj => obj.val2);
点赞
评论
lillo
lillo

Since you want to construct a new object on iterations that pass, you can use .map to transform all of the passing objects after filtering:

const result = [
   {val: 0, val2: 'a'},
   {val: 1, val2: 'b'},
   {val: 2, val2: 'c'},
   {val: 3, val2: 'd'}
]
  .filter(obj => obj.val > 1)
  .map(({ val2 }) => ({ val2 }));
console.log(result);

或者,仅对数组进行一次迭代:

const input = [
   {val: 0, val2: 'a'},
   {val: 1, val2: 'b'},
   {val: 2, val2: 'c'},
   {val: 3, val2: 'd'}
]
const result = [];
for (const { val, val2 } of input) {
  if (val > 1) result.push({ val2 });
}
console.log(result);
点赞
评论
俄还好
俄还好

您必须改变思维方式,并了解如何实现目标。

Look, you wanna get all val2 property values only when value of property val is grather than 1 - in this case you have to split your job to 2 microtasks:
1. filter the array and remove all useless cases
2. get your property value

干得好:

const arr = [
  { val: 0, val2: 'a' },
  { val: 1, val2: 'b' },
  { val: 2, val2: 'c' },
  { val: 3, val2: 'd' },
];

const res = arr.filter(({ val }) => val > 1)
                .map(({ val2 }) => ({val2}));

console.log(res)
点赞
评论
kalias
kalias

you want to use reduce for this, keep it to 1 iteration and only push items in the array that you want to keep.

const result = [
   {val: 0, val2: 'a'},
   {val: 1, val2: 'b'},
   {val: 2, val2: 'c'},
   {val: 3, val2: 'd'}
].reduce((prev, obj) => {
    if (obj.val > 1)
        prev.push({ val2: obj.val2 });
    return prev;
}, []);

console.log(result)
点赞
评论