我想将此数据数组过滤为州和城市数组。我如何使用 lodash 或任何其他更好的方法而不是 for 循环和维护额外的数组来实现这一点。
data: [
{ id: 1, name: Mike, city: philps, state: New York},
{ id: 2, name: Steve, city: Square, state: Chicago},
{ id: 3, name: Jhon, city: market, state: New York},
{ id: 4, name: philps, city: booket, state: Texas},
{ id: 5, name: smith, city: brookfield, state: Florida},
{ id: 6, name: Broom, city: old street, state: Florida},
]
哪个用户点击state
,出现状态列表。
{state: New York, count: 2},
{state: Texas, count: 1},
{state: Florida, count: 2},
{state: Chicago, count: 1},
当用户单击特定州时,将显示该州的城市
列表。对于前。当用户点击纽约州时,
{id:1, name: Mike, city: philps}
{id:3, name: Jhon, city: market}
最佳答案
您可以使用 native
javascript 通过应用 filter
方法来执行此操作,该方法接受 parameter callback
提供的函数.
let data = [ { id: 1, name: 'Mike', city: 'philps', state:'New York'}, { id: 2, name: 'Steve', city: 'Square', state: 'Chicago'}, { id: 3, name: 'Jhon', city: 'market', state: 'New York'}, { id: 4, name: 'philps', city: 'booket', state: 'Texas'}, { id: 5, name: 'smith', city: 'brookfield', state: 'Florida'}, { id: 6, name: 'Broom', city: 'old street', state: 'Florida'}, ]
data = data.filter(function(item){
return item.state == 'New York';
}).map(function({id, name, city}){
return {id, name, city};
});
console.log(data);
另一种方法是使用arrow
函数。
let data = [ { id: 1, name: 'Mike', city: 'philps', state:'New York'}, { id: 2, name: 'Steve', city: 'Square', state: 'Chicago'}, { id: 3, name: 'Jhon', city: 'market', state: 'New York'}, { id: 4, name: 'philps', city: 'booket', state: 'Texas'}, { id: 5, name: 'smith', city: 'brookfield', state: 'Florida'}, { id: 6, name: 'Broom', city: 'old street', state: 'Florida'}, ]
data = data.filter((item) => item.state == 'New York').map(({id, name, city}) => ({id, name, city}));
console.log(data);
关于javascript - 如何过滤 native react 中的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46862976/