我需要匹配来自两个 JSON 源的值。当“城市”数组的嵌套更浅一层
(只是一组对象)时,以这种方式使用javascript
find
方法对我有用,但它不适用于更深的嵌套(其中的一组对象一组对象).
本质上,我想做的是循环遍历
feeds[0].feed.details.place
数组并为每个数组找到匹配的cities.CountyPlaces.PlaceFIPSCode
值。
// console.log(feeds[0].feed.details.place);
// console.log(cities[1].CountyPlaces[2].PlaceName);
feeds[0].feed.details.place.map(async (arrItem, z) => {
console.log('arrItem: ', arrItem);
const cityMatch = await cities.find((cityObject, i) => {
// console.log(i, 'cityObject: ', cityObject);
arrItem === cityObject.PlaceName;
});
if (cityMatch !== undefined) {
// --> THIS IS WHERE I NEED TO MANIPULATE MATCHING DATA
console.log(
z,
'cityMatch: ',
arrItem,
cityMatch.PlaceName,
cityMatch.PlaceFIPSCode
);
} else {
// there should be a defined match for every "place" and no else results
console.log(z, '💥 cityMatch UNDEFINED', arrItem);
}
});
这是我使用的数据示例,具有相同的嵌套:
const feeds = [
{
feed: {
record: '0002',
details: {
county: ['Alameda'],
place: ['Alameda', 'Berkeley', 'Oakland'],
},
},
},
];
const cities = [
{
CountyName: 'San Francisco',
CountyFIPSCode: '075',
CountyPlaces: [
{
PlaceName: 'San Francisco',
PlaceFIPSCode: '67000',
},
],
},
{
CountyName: 'Alameda',
CountyFIPSCode: '001',
CountyPlaces: [
{
PlaceName: 'Alameda',
PlaceFIPSCode: '00562',
},
{
PlaceName: 'Albany',
PlaceFIPSCode: '00674',
},
{
PlaceName: 'Berkeley',
PlaceFIPSCode: '06000',
},
{
PlaceName: 'Emeryville',
PlaceFIPSCode: '22594',
},
{
PlaceName: 'Oakland',
PlaceFIPSCode: '53000',
},
],
},
];
您可以根据
cities
匹配CountyName
过滤details.county[0]
数组,然后根据CountyPlaces
在PlaceName
中过滤匹配城市的details.place
:
const feeds = [
{
feed: {
record: '0002',
details: {
county: ['Alameda'],
place: ['Alameda', 'Berkeley', 'Oakland'],
},
},
},
];
const cities = [
{
CountyName: 'San Francisco',
CountyFIPSCode: '075',
CountyPlaces: [
{
PlaceName: 'San Francisco', PlaceFIPSCode: '67000',
},
],
},
{
CountyName: 'Alameda',
CountyFIPSCode: '001',
CountyPlaces: [
{
PlaceName: 'Alameda', PlaceFIPSCode: '00562',
},
{
PlaceName: 'Albany', PlaceFIPSCode: '00674',
},
{
PlaceName: 'Berkeley', PlaceFIPSCode: '06000',
},
{
PlaceName: 'Emeryville', PlaceFIPSCode: '22594',
},
{
PlaceName: 'Oakland', PlaceFIPSCode: '53000',
},
],
},
];
const county = feeds[0].feed.details.county[0];
const places = feeds[0].feed.details.place;
const result = cities
.filter(city => city.CountyName == county)[0]
.CountyPlaces.filter(({ PlaceName }) => places.includes(PlaceName))
console.log(result)
如果我明白你的问题,你能试试下面的代码吗?
const cityMatch = await cities.find((cityObject, i) => {
// console.log(i, 'cityObject: ', cityObject);
cityObject.CountyPlaces.some(p=>p.PlaceName===arrItem)
});