比較兩個不同 JSON 陣列中的值:逐步指南
P粉418214279
P粉418214279 2024-04-01 00:19:48
0
1
380

   

 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 的陣列物件

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板