如何过滤本机反应中的对象数组? [英] How to filter array of objects in react native?
问题描述
我想将此数据数组过滤为州和城市数组.我如何使用 lodash 或任何其他更好的方法而不是 for 循环和维护额外的数组来实现这一点.
I want to filter this data array into state and city array. How can I achieve this using lodash or any other better way rather than for loop and maintaining extra arrays.
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
,状态列表出现.
which user click state
, list of state appears.
{state: New York, count: 2},
{state: Texas, count: 1},
{state: Florida, count: 2},
{state: Chicago, count: 1},
当用户点击特定州时,会出现该州的城市
列表.例如.当用户点击纽约州时,
When user click particular state, list of cities
of that state appears. For ex. when user clicks New York state,
{id:1, name: Mike, city: philps}
{id:3, name: Jhon, city: market}
推荐答案
使用 lodash,你可以使用 _.filter
对象为 _.matches
iteratee shorthand 用于使用给定的键/值对过滤对象和
With lodash, you could use _.filter
with an object as _.matches
iteratee shorthand for filtering the object with a given key/value pair and
使用 _.countBy
和 _.map
用于获取状态计数.
use _.countBy
with _.map
for getting a count of states.
var 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' }];
console.log(_.filter(data, { state: 'New York' }));
console.log(_
.chain(data)
.countBy('state')
.map((count, state) => ({ state, count }))
.value()
);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
这篇关于如何过滤本机反应中的对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!