Comparing values ​​in two different JSON arrays: a step-by-step guide
P粉418214279
P粉418214279 2024-04-01 00:19:48
0
1
406

   

 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)

I want to compare two arrays, get the id and name of the fruit that does not exist in the food and is not equal to 1, and then save the result to a new array.

For example, if there are oranges in the food array, the result should store the id and name of the fruit that does not exist in the food and delete it! =1. (apple, cherry).

P粉418214279
P粉418214279

reply all(1)
P粉547170972

Your code has a syntax error, here is the updated error:

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 

The result will return an array object containing cherry

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template