如何检查数组是否具有具有特定属性的对象,然后找到该属性?

时间:2020-05-26 10:26:27

标签: javascript arrays properties

我有一个看起来像这样的数组:

var arr = [
  {name: "Joe", id: "p01"}
];

我首先要检查输入是否与具有相同name属性的任何内容匹配。例如,如果用户输入“ Steven”,我希望它检查名称为“ Steven”的任何对象。

其次,我想从他们输入的内容中获取id,如果存在的话。

抱歉,这是一个大问题。

5 个答案:

答案 0 :(得分:0)

const arr = [
  {name: "Joe", id: "p01"}
];

//need to find array item where object.name is Joe - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
const obj = arr.find(item => {
    //item = {name: "Joe", id: "p01"}
    return item.name === 'Joe'
});

//obj = {name: "Joe", id: "p01"}
//check if item exists and return id value;
const id = obj && obj.id;

//to filter array and get only items where name is Joe - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
const items = arr.filter(item => item.name === 'Joe');
//items = [{name: "Joe", id: "p01"}]

//to get the list of ids with condition
const ids = arr.reduce((results, obj) => {
 if (obj.name === "Joe") results.push(obj.id);
}, [])
//ids = ["p01"]

//one line solution
const { id } = arr.find(item => item.name === 'Joe') || {};

答案 1 :(得分:0)

const foundItem = arr.find(item => item.name === searchQuery) // searchQuery = Steven

if (foundItem === -1) {
  console.log("Item not found")
} else {
  console.log("Item found", foundItem)
  console.log("Item id: ", fountItem.id)
}

答案 2 :(得分:0)

您可以这样做,希望对您有帮助

blank=True

答案 3 :(得分:0)

为了获得id个匹配元素的列表:

var arr = [
     {name: "Joe", id: "p01"},
     {name: "Bob", id: "p02"},
     {name: "Joe", id: "p03"},
];
let input = "Joe";
let list = [];
for(let i = 0; i < arr.length; i++){
     if(arr[i].name == input){
          list.push(arr[i].id)
     }
}
console.log(list)

答案 4 :(得分:0)

也可以通过filter完成。

var arr = [
  {name: "Joe", id: "p01"},
  {name: "Steve", id: "p02"},
  {name: "Smith", id: "p01"},
];



console.log(arr.filter(i=>i.name.includes('Ste')))
   var ids = arr.filter(i=>i.name.includes('Ste')).map(k=>k.id);
console.log(ids);