Javascript:在深度嵌套的数组和对象中查找匹配的属性值



我需要匹配两个JSON源的值。使用javascriptfind方法这种方式对我来说是有效的,当嵌套"cities"Array是一个更浅的层次(仅仅是一个对象数组),但是它不能用于更深层次的嵌套(对象数组中的对象数组)

本质上,我要做的是循环通过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',
},
],
},
];

可以根据匹配details.county[0]CountyNamecities数组进行筛选,然后根据details.place中的PlaceName对匹配城市的CountyPlaces进行筛选:

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 = cities.find((cityObject, i) => {
// console.log(i, 'cityObject: ', cityObject);
return cityObject.CountyPlaces.some(p=>p.PlaceName===arrItem)

});

只匹配位置

const placeMatch = cityMatch.CountyPlaces.filter(p=>p.PlaceName===arrItem)[0]

最新更新