const fruits = [{id: '1', name: 'Apple'}, {id: '2', name: 'Orange'}, {id: '3', name: 'Cherry'}]; const food=[{id: '1', food_name: 'Orange', deleted:"0"}, {id: '2', food_name: 'Bread' ,deleted:"0"}, {id: '3', food_name: 'Cheese', deleted:"0"}, {id: '4', food_name: 'Apple', deleted:"1"}, {id: '5', food_name: 'Salt',deleted:"0"} ] //Code that I tried: var dep_data = []; var foodSet = new Set(food.map(item => item.food_name)); for (var j = 0; j < fruits.length; j++) { if (!foodSet.has(fruits[j].name) && fruits[j].deleted !== "1") { dep_data.push({ id: fruits[j].id, name: fruits[j].name }); } } console.log(dep_data)
我想比較兩個數組,取得食物中不存在且刪除不等於1的水果的id和名稱,然後將結果儲存到新數組中。
例如,食物數組中存在橙子,結果應儲存食物中不存在的水果的 id 和名稱,並刪除! =1。 (蘋果、櫻桃)。
P粉5471709722024-04-01 20:45:50
您的程式碼有語法錯誤,這是更新的錯誤:
const fruits = [ { id: '1', name: 'Apple' }, { id: '2', name: 'Orange' }, { id: '3', name: 'Cherry' } ]; const food = [ { id: '1', food_name: 'Orange', deleted: "0" }, { id: '2', food_name: 'Bread', deleted: "0" }, { id: '3', food_name: 'Cheese', deleted: "0" }, { id: '4', food_name: 'Apple', deleted: "1" }, { id: '5', food_name: 'Salt', deleted: "0" } ]; var dep_data = []; var foodSet = new Set(food.map(item => item.food_name)); for (var j = 0; j < fruits.length; j++) { if (!foodSet.has(fruits[j].name) && fruits[j].deleted !== "1") { dep_data.push({ id: fruits[j].id, name: fruits[j].name }); } } console.log(dep_data);
結果將傳回一個包含 cherry
的陣列物件