Home  >  Q&A  >  body text

Comparing values ​​in two different JSON arrays: a step-by-step guide

   

 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粉418214279P粉418214279183 days ago300

reply all(1)I'll reply

  • P粉547170972

    P粉5471709722024-04-01 20:45:50

    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 < 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);
    
    

    The result will return an array object containing cherry

    reply
    0
  • Cancelreply