判断数组里的对象属性中是否等于某个值
export const inArray = (search, array) => {
// search要查找的属性值,array,数组
if (!array) {
return false
} else {
for (const i of array) {
// for of 遍历数组 i为数组的每个元素
const res = i
// console.log(i);
for (const j in res) {
// for in 遍历对象,j为对象的属性值
if (res[j] === search) {
return res
}
}
}
}
}
如果存在的话返回的是数组里的那个对象
例子:
const list = [
{ date: "2023-04-26", play: 1, work: 2, study: 0, sport: 0 },
{ date: "2023-04-27", play: 0, work: 0, study: 0, sport: 0 },
{ date: "2023-04-30", play: 3, work: 0, study: 0, sport: 0 },
{ date: "2023-05-04", play: 0, work: 0, study: 5, sport: 0 },
{ date: "2023-04-26", play: 2, work: 0, study: 0, sport: 0 },
{ date: "2023-05-03", play: 0.5, work: 0, study: 0, sport: 0 },
{ date: "2023-05-04", play: 5, work: 7, study: 2, sport: 6 },
{ date: "2023-05-05", play: 1.5, work: 3, study: 4, sport: 0 },
{ date: "2023-05-07", play: 0, work: 0, study: 0, sport: 0 },
{ date: "2023-05-08", play: 8, work: 1, study: 0, sport: 0 },
];
// 查找数组里是否有date为'2023-05-07'的值
console(inArray('2023-05-07',list))
// 输出:{ date: "2023-05-07", play: 0, work: 0, study: 0, sport: 0 }
console(inArray('2023-05-12',list))
// 输出:false