【问题标题】:What is the best way to compare two arrays and flag the updated value?比较两个数组并标记更新值的最佳方法是什么?
【发布时间】:2021-04-14 01:59:30
【问题描述】:

目前,我已经序列化了一个在加载页面时定义的表单数组 (initial_form_array)。更改表单字段后,我创建了一个新的表单序列化数组 (updated_form_array)。在进行表单的下一步之前,我解析初始数组并将其与更改后的表单数组进行比较,以查明哪个值已更改。为此,我以下列方式使用$.inArray

if(initial_form_array != updated_form_array){
  
   $.each( updated_form_array, function( key, value ) {

       var name  = value['name'],
             value = value['value'];

       var comparison_value = $.inArray( value,  initial_form_array );
       if( comparison_value == -1 ) {
           console.log( "found an edit" );
    }
  }
}

所以在上面的例子中你可以看到,当found an edit 语句被记录到控制台时,这是因为初始表单数组中不存在该值。问题是这只是检查值是否在初始数组中。因此,如果值已从 123 更改为仅 23,它将不会到达 found an edit 位置,因为 23123 内。

在这种情况下,有没有更好的方法来做到这一点?如果这是一个很好的方法,有没有办法进一步澄清比较是为了精确匹配,而不是仅仅确定值匹配是否在数组中?

【问题讨论】:

  • $.inArray 不应该为部分匹配返回 true。有什么例子吗?
  • 如果初始表单数组是相同结构的对象 {name:'foo', value:123} 这种匹配方法将不起作用。将使用$.inArray 将原始值与整个对象进行比较

标签: jquery arrays compare key-value


【解决方案1】:

注意你不能比较两个数组做if(arr1 === arr2)。这只检查它们是否是完全相同的数组对象,而不检查数组中的内容。

以下内容应该可以为您提供一些帮助

// iniital on page load
const initial_form_array = getArr();
// create a map object for easy loop using name as key
const init_map = new Map(initial_form_array.map(o=>[o.name,o.value]))

// change some values for demo and log differences
doFormChanges();
logDiff();

// log manual changes
$('#myForm').submit(e => {
  e.preventDefault();  
  logDiff();
})


function logDiff(){
    console.clear()
    const update_arr = getArr();
    const diff = update_arr.filter(o => init_map.get(o.name) !== o.value)
                            .map(o => ({...o, prev_val: init_map.get(o.name)}));
    if(!diff.length){
       console.log('No changes')
    }else{
       console.log('Diff from original:',diff);
    }
}


function getArr() {
  return $('#myForm').serializeArray();
}

function doFormChanges() {
  $('[name="age"]').val(30);
  $('[name="message"]').val('Yahoo');
}
form div {
  padding: 10px;
  width: 30%;
  float: left
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
  <div><button>Test Me</button></div>
  <div><input name="fname" value="Foo"></div>
  <div><input name="lname" value="Bar"></div>
  <div><input name="age" value="37"></div>
  <div>
    <select name="location">
      <option value=""> Pick one</option>
      <option value="Australia" selected="">Australia</option>
      <option value="India">India</option>
    </select>
  </div>
  <div><textarea name="message">Blah blah blah</textarea></div>


</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多