簡體   English   中英

檢查一個數組對象是否包含 JavaScript 中另一個數組的任何元素,然后根據打印

[英]Check if an array object contains any element of another array in JavaScript and then print according

我有一個包含“山姆”一詞的數組。

selectedItem = ['sam']

然后我有一個對象數組

   persons = [
  {name: 'sam', pin: u393842},
  {name: 'fred', pin: u82832}
]

我想返回數組中具有相同名稱和匹配的 selectedItem 的對象。

你可以這樣做:

const selectedItem = ['sam'];

const persons = [
  {name: 'sam', id: u393842},
  {name: 'fred', id: u82832}
];

const selectedPersons = persons.filter(function(person) {
  return selectedItem.includes(person.name);
});

console.log(selectedPersons);

const selectedItem = ['sam'];

const persons = [
  {name: 'sam', id: 'u393842'},
  {name: 'fred', id: 'u82832'}
];

console.log( persons.find(item => item.name == selectedItem[0] );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM