比较两个不同 JSON 数组中的值:分步指南
P粉418214279
P粉418214279 2024-04-01 00:19:48
0
1
404

   

 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粉418214279
P粉418214279

全部回复(1)
P粉547170972

您的代码有语法错误,这是更新的错误:

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 

结果将返回一个包含 cherry 的数组对象

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板