在 JavaScript 中,如何設定陣列中物件的屬性為真/假,判斷該物件的 id 是否與另一個物件陣列中的任何 id 匹配?


本文將要執行的任務是“在 JavaScript 中,設定陣列中物件的屬性為真/假,判斷該物件的 id 是否與另一個物件陣列中的任何 id 匹配”。在深入本文之前,讓我們先簡單瞭解一下 JavaScript 中的物件和陣列。

JavaScript 中,物件是一個獨立的實體,具有屬性和型別。JavaScript 物件具有指定其屬性的屬性。

透過使用陣列,可以在單個變數中儲存多個值。將其與只能容納一個值的變數進行比較。陣列中的每個專案都與一個關聯的數字相關聯,您可以透過使用該數字來訪問該專案,稱為數字索引。JavaScript 中的陣列從索引零開始,並且可以使用各種操作進行更改。

語法

以下是 JavaScript 中陣列的語法 -

const array_name = [item1, item2, ...]; 

讓我們深入本文,瞭解“如何在 JavaScript 中設定陣列中物件的屬性為真/假,判斷該物件的 id 是否與另一個物件陣列中的任何 id 匹配”。您可以使用 reduce() 結合 map()。

JavaScript 中的 reduce()

JavaScript 中的 reduce() 方法用於將(回撥)函式應用於陣列中的每個元素,從而生成單個輸出值。它對陣列中存在的每個元素執行回撥函式,不包括陣列中的空洞。

然後它將前一次迭代的結果儲存到累加器引數中,並將其傳遞到後續迭代,直到所有值都處理完畢。

語法

以下是 JavaScript 中 reduce() 的語法 -

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

JavaScript 中的 map()

任何型別的資料都可以在對映中用作,它還會記住其元素出現的順序。它用於透過重複遍歷陣列中的每個元素來建立一個新的陣列

語法

以下是 JavaScript 中 map() 的語法 -

array.map(function(currentValue, index, arr), thisValue)

為了更好地理解,讓我們看看以下示例。

示例

在下面的示例中,我們使用reduce()結合map()

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      let array_1=[{"id":1,"name":"bmw"},{"id":22,"name":"audi"},{"id":3,"name":"bullet"}]
      let array_2=[{"id":1,"name":"benz"},{"id":82,"name":"rx100"},{"id":3,"name":"bullet"},]
      document.write("Contents of the first array: ", JSON.stringify(array_1),"<br>");
      document.write("Contents of the second array: ", JSON.stringify(array_2),"<br>");
      const o = array_2.reduce((r, e) => (r[e.id] = true, r), {})
      const result = array_1.map(e => ({ ...e, matches: o[e.id] || false}))
      document.write("Result of the comparison: ",JSON.stringify(result));
   </script>
</body>
</html>

示例

考慮以下示例,其中我們使用迴圈。

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      let tutorial_1 = [
         { id: 5, car: 'cruze' },
         { id: 2, car: 'beats' },
         { id: 3, car: 'sail' },
      ];
      let tutorial_2 = [
         { id: 1, car: 'city' },
         { id: 80, car: 'verna' },
         { id: 3, car: 'electra' },
      ];
      tutorial_1.forEach(item_1 => {
         for (let i = 0; i < tutorial_2.length; i++) {
            item_1.matches = tutorial_2[i].id === item_1.id
         }
      });
      document.getElementById("tutorial").innerHTML=    JSON.stringify(('matched_array', tutorial_1));
   </script>
</body>
</html>

示例

在下面的示例中,我們聲明瞭一個固定陣列,並使用 every() 方法進行比較。

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      let fixed = ["abc", "def", "ghi"];
      let Array1 = [{
         bike: "rx100",
         id: "abc"
      }, {
         bike: "pulsar",
         id: "def"
      }, {
         bike: "splendor",
         id: "ghi"
      }];
      let conA1 = Array1.every(elem => fixed.includes(elem.id));
      document.getElementById("tutorial").innerHTML= conA1;
   </script>
</body>
</html>

當指令碼執行時,會觸發事件,該事件將陣列固定陣列進行比較並給出。在這種情況下,它將在 Web 瀏覽器上顯示“true”,因為陣列固定陣列匹配。

更新於: 2023年1月18日

639 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告