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
的数组对象