【问题标题】:How do I check if an array has an object with a certain property and then find that property?如何检查数组是否具有具有特定属性的对象,然后找到该属性?
【发布时间】:2020-05-26 10:26:27
【问题描述】:

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

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

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

其次,我想获取他们输入的任何内容的id(如果存在)。

抱歉,这是一个大问题。

【问题讨论】:

标签: javascript arrays properties


【解决方案1】:
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') || {};

【讨论】:

  • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
【解决方案2】:
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)
}

【讨论】:

  • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
【解决方案3】:

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

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

let searchQuery = 'Joe'
let finalResult = arr.find(({name}) => name.includes(searchQuery));
finalResult = (finalResult && finalResult.id) ? finalResult.id :"No Match Found"
console.log(finalResult);

【讨论】:

    【解决方案4】:

    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);

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2012-04-16
      • 2017-10-09
      • 2020-06-08
      • 2012-11-12
      • 2013-07-03
      • 2010-09-13
      • 1970-01-01
      相关资源
      最近更新 更多