如果两个数组与 JavaScript 中的某个值匹配,我们如何从数组中打印值?

How can we print value from an array if two array matches with some value in JavaScript?

我必须比较两个对象数组并检查相同的项目是否包含在另一个数组中。

const array1 = [
    { item: "orange", id: 11 },
    { item: "apple", id: 12 },
];

const array2 = [10, 11, 12];

如果我检查 array1.How 中 array2 的值​​,我可以在映射 array2 时得到如下输出吗?

  Item does'nt exists
  orange 
  apple


  
 

试试这个

const array1 = [{
    item: 'orange',
    id: 11
}, {
    item: 'apple',
    id: 12
}]

const array2 = [10, 11, 12]

for (const x of array2) {
   //find element from array
   const searchElem = array1.find((item) => item.id == x)
   
   if (searchElem) {
        console.log(searchElem.item + " for " + x)
    } else {
        console.log("Item doesn't exists for", x)
    }

}

您可以使用 map and find

轻松实现此结果

const array1 = [
  { item: "orange", id: 11 },
  { item: "apple", id: 12 },
];
const array2 = [10, 11, 12];

const result = array2.map((id) => {
  const itemFound = array1.find((o) => o.id === id);
  if (itemFound) return `${itemFound.item} for ${itemFound.id}`;
  else return `Item does'nt exists for 10`;
});

console.log(result);

如果我正确理解了这个问题,您要做的是确认数组 2 中的每个元素在数组 1 中是否存在具有特定 属性 的对象。

如果你想检查每一个,看看它是否存在,你可以这样做:

const fruits = [
  {item: 'orange', id: 11},{item: 'apple', id: 12}
]

const fruitIds = fruits.map((fruit) => fruit.id);

const ids = [10, 11, 12]

ids.forEach((id) => { 
  console.log(`${id} exists in fruits: ` + fruitIds.includes(id))
})

或者如果你想检查数组中的每个 ID 是否有水果,而你只关心 true / false 是否都存在,那么你可以这样做:

const fruits = [
  {item: 'orange', id: 11}, 
  {item: 'apple', id: 12}
]

const fruitIds = fruits.map((fruit) => fruit.id).sort();

const ids = [10, 11, 12];

console.log("There is a fruit for each ID in ID array: ", JSON.stringify(ids) === JSON.stringify(fruitIds))

如果这不能回答您的问题,那么请编辑并尝试使您的问题更清楚,我也会对我的回答做同样的事情。

请注意,最后一个片段只是比较 JavaScript 中的数组或对象的一种方法。

通过比较 JavaScript 中的两个数组来获取常见项的最简单方法是使用 filter() and includes() 数组函数。

例如:

const array1 = [
      { item: "orange", id: 11 },
      { item: "apple", id: 12 },
];

const array2 = [10, 11, 12];

const matchedArray = array1.filter((item) => array2.includes(item.id));

console.log(matchedArray);

我们不需要使用 for 循环、forEach、map 和 find 函数。

试试这个代码我认为它会解决你的问题

  • 我已经写了一些关于 javascript 代码的评论,它可能会对您有所帮助。

const array1=[{item:'orange', id:11},{item:'apple', id:12}]
const array2=[10,11,12]

function removeDuplicates(array, matchKey) {
    return array.filter((value, index) => {
        return array.indexOf(array.find(value_1 => value_1[matchKey] == value[matchKey])) == index
    });
}

// send "id" parameter if you want to filter array by id
// ex: removeDuplicates(array1, 'id')
const filteredArray1 = removeDuplicates(array1, 'item');

array2.forEach(id => {
    let foundItem = array1.find(itemObj => itemObj.id == id);
    if(foundItem == null) {
        console.log(`Item doesn't exists for ${id}`);
    }else {
        console.log(`${foundItem.item} for ${id}`);
    }
});

这是一种使用 Map, though with a bit of tweaking it could use a normal object instead of Map. The map indexes the items in array1 by id and then allows you to look for the item in the map (using has() or get()); if it doesn't exist you can fall back to the default string. ?? is the nullish coalescing operator 的方法,它允许您为表达式提供一个术语,应该是 ?? 之前的值为空或未定义。

const array1 = [{ item: "orange", id: 11 }, { item: "apple", id: 12 }];
const array2 = [10, 11, 12];
const default_string = "Item does'nt exists";

const array1_map = new Map(array1.map((o) => [o.id, o]));

const res = array2.map( (id) => array1_map.get(id)?.item ?? default_string );

console.log(res);