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