我需要匹配来自两个JSON源的值。使用javascript find
方法,当“cities”数组的嵌套更浅 (只是一个对象数组) 时,这种方法对我有效,但它不适用于更深的嵌套 (对象数组中的对象数组)。
本质上,我试图做的是遍历feeds[0].feed.details.place
数组并为每个数组找到匹配的cities.CountyPlaces.PlaceFIPSCode
值。我实际上需要整个“place”对象,因此我可以为每个匹配使用其中的任何数据。
// 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',
},
],
},
];
2条答案
按热度按时间uqzxnwby1#
如果我理解了你的问题,你能试试下面的代码吗?
获取唯一匹配位置
q5iwbnjs2#
您可以根据
CountyName
匹配details.county[0]
来过滤cities
数组,然后根据PlaceName
在details.place
中过滤匹配城市的CountyPlaces
: