4 回答
TA贡献1848条经验 获得超2个赞
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') || {};
TA贡献1824条经验 获得超5个赞
它也可以做到。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);
TA贡献1779条经验 获得超6个赞
你可以这样做,希望这会帮助你
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);
TA贡献1963条经验 获得超6个赞
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)
}
添加回答
举报