假设我们有一个像这样的对象数组-
const arr = [ { id : "23", name : "Item 1", isActive : true}, { id : "25", name : "Item 2", isActive : false}, { id : "26", name : "Item 3", isActive : false}, { id : "30", name : "Item 4", isActive : true}, { id : "45", name : "Item 5", isActive : true} ];
我们需要编写一个JavaScript函数,该函数接受一个这样的对象,并返回所有对“ isActive”属性具有真实值的对象的“ id”属性值的数组。
为此的代码将是-
const arr = [ { id : "23", name : "Item 1", isActive : true}, { id : "25", name : "Item 2", isActive : false}, { id : "26", name : "Item 3", isActive : false}, { id : "30", name : "Item 4", isActive : true}, { id : "45", name : "Item 5", isActive : true} ]; const findActive = (arr = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const obj = arr[i]; const { id, isActive } = obj; if(isActive){ res.push(id); } }; return res; }; console.log(findActive(arr));
输出结果
控制台中的输出将是-
[ '23', '30', '45' ]