我有一个看起来像这样的数组:
var arr = [
{name: "Joe", id: "p01"}
];
我首先要检查输入是否与具有相同name
属性的任何内容匹配。例如,如果用户输入“ Steven”,我希望它检查名称为“ Steven”的任何对象。
其次,我想从他们输入的内容中获取id
,如果存在的话。
抱歉,这是一个大问题。
答案 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);