如何用Node.js和React筛选JSON中name含Delhi的对象
筛选包含"Delhi"的地点数据(Node.js + React实现)
Node.js 后端实现
直接用数组的filter方法就能完成筛选,核心逻辑是检查每个对象的name属性是否包含"Delhi"字符串。
// 原始地点数据 const locations = [ { "_id": "1", "name": "ShalimarBhagh", "city_id": "1", "location_id": "1", "country_name": "India" }, { "_id": "2", "name": "Janpat, Delhi", "city_id": "1", "location_id": "2", "country_name": "India" }, { "_id": "3", "name": "MSP, Delhi", "city_id": "1", "location_id": "3", "country_name": "India" }, { "_id": "4", "name": "MSP, Pune", "city_id": "2", "location_id": "4", "country_name": "India" }, { "_id": "5", "name": "Anand Pur", "city_id": "1", "location_id": "5", "country_name": "India" } ]; // 筛选name包含"Delhi"的对象 const delhiLocations = locations.filter(location => location.name.includes('Delhi')); // 输出格式化后的结果 console.log(JSON.stringify(delhiLocations, null, 2));
运行后输出结果:
[ { "_id": "2", "name": "Janpat, Delhi", "city_id": "1", "location_id": "2", "country_name": "India" }, { "_id": "3", "name": "MSP, Delhi", "city_id": "1", "location_id": "3", "country_name": "India" } ]
React 前端实现
在React组件中,结合状态管理和filter方法处理数据,同时渲染筛选结果:
import { useState, useEffect } from 'react'; function DelhiLocations() { const [locations, setLocations] = useState([]); const [filteredLocations, setFilteredLocations] = useState([]); // 模拟初始化数据(实际项目可替换为API请求) useEffect(() => { const rawData = [ { "_id": "1", "name": "ShalimarBhagh", "city_id": "1", "location_id": "1", "country_name": "India" }, { "_id": "2", "name": "Janpat, Delhi", "city_id": "1", "location_id": "2", "country_name": "India" }, { "_id": "3", "name": "MSP, Delhi", "city_id": "1", "location_id": "3", "country_name": "India" }, { "_id": "4", "name": "MSP, Pune", "city_id": "2", "location_id": "4", "country_name": "India" }, { "_id": "5", "name": "Anand Pur", "city_id": "1", "location_id": "5", "country_name": "India" } ]; setLocations(rawData); }, []); // 数据更新时自动筛选 useEffect(() => { const result = locations.filter(location => location.name.includes('Delhi')); setFilteredLocations(result); }, [locations]); return ( <div> <h2>包含Delhi的地点</h2> <ul> {filteredLocations.map(location => ( <li key={location._id}> <strong>{location.name}</strong> - 城市ID: {location.city_id} </li> ))} </ul> {/* 展示格式化的JSON结果 */} <pre>{JSON.stringify(filteredLocations, null, 2)}</pre> </div> ); } export default DelhiLocations;
组件会同时渲染筛选后的地点列表和格式化的JSON结果。
内容的提问来源于stack exchange,提问作者Suman kumar
相关产品推荐
相关产品推荐

