我想把这个数据数组过滤成州和市array.如何使用lodash或其他更好的方法实现这一点,而不是使用循环和维护额外的array.

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},

当用户单击特定状态时,将显示该状态的cities个列表.例如,当用户点击纽约州,

{id:1, name: Mike, city: philps}
{id:3, name: Jhon, city: market}

推荐答案

使用lodash,可以将_.filter与对象一起使用,将其作为101 iteratee shorthand来过滤具有给定键/值对的对象,并

使用_.countBy_.map来计算状态数.

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>

React-native相关问答推荐

使用FETCH发送BLOB/文件时为空

React Native 在每个页面加载时调用数据库

收到错误Constants.platform.ios.model已被弃用,以支持 expo-device

为什么将字符串写入文件然后将相同的文件作为字符串读取会导致不同的字符串?

React Native - remount / reset / reload屏幕的最佳方式是什么?

无法在 React Native iOS 模拟器中按 URI 显示图像

React Native TextInput 没有获得焦点

react-native 链接仅适用于一个项目(Android 或 iOS)

是否可以在 React Native 中隐藏BugReporting extraData?

React Native - SectionList numColumns support

在 React Native (iOS) 中支持动态类型

如何在react-native中设置 FlatList 的刷新指示器?

SyntaxError:Strict mode does not allow function declarations in a lexically nested statement on a newly created app

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.

如何将 Crashlytics 与 React Native 应用程序集成

react-native如何禁用android开发模式

React Native onLayout 与 React Hooks

I18nManager.forceRTL 不会在首次应用加载时应用更改

在 React-native 上加载图像时出错:Unexpected character

列之间的 React Native FlatList 分隔符