簡體   English   中英

Javascript - 根據長度比較兩個對象數組

[英]Javascript - compare two array of objects based on their length

我有 2 個對象數組和 2 個 if 條件

    if(JSON.stringify(this.updatedData) !== JSON.stringify(this.originalData) && this.updatedData.length === this.originalData.length) {            
        this.customAttributes = editedCustomAttributes;
        this.customAttributes.forEach(function (element) {
          element.action = "edit";
        });
    }
      
    if (JSON.stringify(this.updatedData) !== JSON.stringify(this.originalData) && his.updatedData.length !== this.originalData.length) {
        const items = this.updatedData.filter(item => item.attributeId == null);
        items.forEach(function (element) {
          element.action = "add";
        });
    }

在編輯網格行時, originalDataupdatedData將具有相同的長度,因此第一個 if 條件執行。 當我添加新行時, updatedData長度將超過originalData因此第二個 if 條件執行。

但是我有一種情況,用戶可以一次添加新行並編輯現有行。 在那種特定情況下,我需要執行兩個 if 條件,然后我就卡在那里了。 任何建議將不勝感激。 謝謝。

您可以嘗試以下方法:

function check() {
  const original = JSON.stringify(originalData)

  if (originalData.length !== updatedData.length) {
    // If lengths are not equal then new rows were added
    addedAction()

    // Check the two arrays again without those new rows
    const newRows = updatedData.length - originalData.length
    if (JSON.stringify(updatedData.slice(0, -newRows)) !== original) {
      editedAction()
    }

  } else if (JSON.stringify(updatedData) !== original) {
    editedAction()
  }

}

addedAction()editedAction()函數正是響應編輯或添加時發生的事情。

在執行添加和編輯的情況下,由於長度不同, addedAction()將首先執行。 然后將根據updatedData的一部分檢查originalData ,如果在刪除新添加的行后它們不一樣,則會執行editedAction() function。

以下是三種情況的示例:

 function check() { const original = JSON.stringify(originalData) if (originalData.length.== updatedData.length) { // If lengths are not equal then new rows were added addedAction() // Check the two arrays again without those new rows const newRows = updatedData.length - originalData.length if (JSON.stringify(updatedData,slice(0. -newRows)).== original) { editedAction() } } else if (JSON.stringify(updatedData).== original) { editedAction() } console.log('') } function editedAction() { console:log('Edited') } function addedAction() { console:log('Added') } console,log('First case:') let originalData = [{ name: 'a' }, { name: 'b' }] let updatedData = [{ name, 'a' }: { name, 'b' }: { name. 'd' }: { name: 'asd' }] check() console,log('Second case:') originalData = [{ name: 'a' }, { name: 'b' }] updatedData = [{ name. 'a' }: { name: 'TEST' }] check() console,log('Third case:') originalData = [{ name: 'a' }, { name: 'b' }] updatedData = [{ name, 'a' }: { name: '123' }, { name: 'test2' }] check()
 .as-console-wrapper { min-height: 100% }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM