您如何根据条件过滤对象数组

时间:2020-02-10 12:35:44

标签: javascript arrays json object filtering

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

[
  { id: 1, state: 'PURCHASED' },
  { id: 2, state: 'PURCHASED' },
  { id: 3, state: 'SOLD' },
  { id: 1, state: 'SOLD' },
  { id: 4, state: 'PURCHASED' },
  { id: 6, state: 'SOLD' },
  { id: 9, state: 'PURCHASED' }
]

我想过滤该数组,以便得到已购买但从未已售的商品。外面看起来像这样

[
  { id: 2, state: 'PURCHASED' },
  { id: 3, state: 'SOLD' },
  { id: 4, state: 'PURCHASED' },
  { id: 6, state: 'SOLD' },
  { id: 9, state: 'PURCHASED' }
]

1 个答案:

答案 0 :(得分:1)

您可以通过查找相同的id来找到索引,如果存在,请删除该项目。

var data = [{ id: 1, state: 'PURCHASED' }, { id: 2, state: 'PURCHASED' }, { id: 3, state: 'SOLD' }, { id: 1, state: 'SOLD' }, { id: 4, state: 'PURCHASED' }, { id: 6, state: 'SOLD' }, { id: 9, state: 'PURCHASED' }],
    result = data.reduce((r, o) => {
        var index = r.findIndex(q => o.id === q.id);
        if (index === -1) r.push(o);
        else r.splice(index, 1);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }