javascript 如何检查一个数组的键值是否存在于另一个数组中

ee7vknir  于 2023-08-02  发布在  Java
关注(0)|答案(2)|浏览(122)

我有两个数组-

var arr1=  [
{
  VILLAGES_NAME: 'Chozuba Vill.',
  VI_ID: 269292,
  VI_SUBDIST_ID: 1806
},
{
  VILLAGES_NAME: 'Thevopisu',
  VI_ID: 269381,
  VI_SUBDIST_ID: 1806
},
{
  VILLAGES_NAME: 'Chozubasa (UR)',
  VI_ID: 269293,
  VI_SUBDIST_ID: 1806
}
  ];


let arr2=[
{
  LOCALITIES_NAME: 'CHOZUBA PART TWO',
  LOCALITY_ID: 301,
  VILLAGE_ID: 269292
},
{
  LOCALITIES_NAME: 'CHOZUBA PART ONE',
  LOCALITY_ID: 300,
  VILLAGE_ID: 269292
}
  ];

字符串
我想在循环arr 1时检查arr 1的VI_ID的值是否匹配arr 2的VILLAGE_ID中的任何位置。
这是我一直在尝试的,但没有得到预期的结果。

for(let i=0;i<arr1.length;i++)
  {
      if(arr2.includes(arr1[i].VI_ID))
      {
           console.log(arr1[i].VILLAGES_NAME)
      }
      
  }

dzjeubhm

dzjeubhm1#

将条件替换为以下条件:

if (arr2.some(sth=> sth.VILLAGE_ID === arr1[i].VI_ID)) {
    ...
  }

字符串

qxgroojn

qxgroojn2#

你不能只使用一个for循环而不改变其中一个数组类型。举例来说:

var arr1 = [
  {
    VILLAGES_NAME: 'Chozuba Vill.',
    VI_ID: 269292,
    VI_SUBDIST_ID: 1806
  },
  {
    VILLAGES_NAME: 'Thevopisu',
    VI_ID: 269381,
    VI_SUBDIST_ID: 1806
  },
  {
    VILLAGES_NAME: 'Chozubasa (UR)',
    VI_ID: 269293,
    VI_SUBDIST_ID: 1806
  }
];

let arr2 = [
  {
    LOCALITIES_NAME: 'CHOZUBA PART TWO',
    LOCALITY_ID: 301,
    VILLAGE_ID: 269292
  },
  {
    LOCALITIES_NAME: 'CHOZUBA PART ONE',
    LOCALITY_ID: 300,
    VILLAGE_ID: 269292
  }
];

const villageIdSet = new Set(arr2.map(item => item.VILLAGE_ID));

const matchedItems = arr1.filter(item => villageIdSet.has(item.VI_ID));

console.log(matchedItems);

字符串

相关问题