簡體   English   中英

javascript中數組和對象的比較

[英]Comparison between arrays and objects in javascript

我需要比較兩個數組/對象,但我無法弄清楚它們來自兩個不同的來源並且具有不同的格式。

oldData = [{Row_id: "32F993F", Parameter_Type: "String", UOM: "", rowId: "1"},{Row_id: "88898897-988D-4168-B662-2DECEA0E72BD", Parameter: "id", Parameter_Type: "Integer", UOM: "", rowId: "2"}]


newData = [[Row_id: "32F993F", Parameter_Type: "String", UOM: "", rowId: "1"],[Row_id: "88898897-988D-4168-B662-2DECEA0E72BD", Parameter: "id", Parameter_Type: "Integer", UOM: "", rowId: "2"]]

我嘗試使用這些方法進行比較

(JSON.stringify(oldData) == JSON.stringify(newData))
(_.isEqual(oldData, newData)) 

我也試過,

 _.forEach(newData, function (element: any, i: number) {
      dataObj.push(newData);
  });

但沒有什么對我有用。 任何幫助在這里將不勝感激。 補充:如何將 newData 轉換為有效數據? 謝謝。

僅當 newData 是字符串時才可能

 const oldData = [{Row_id: "32F993F", Parameter_Type: "String", UOM: "", rowId: "1"},{Row_id: "88898897-988D-4168-B662-2DECEA0E72BD", Parameter: "id", Parameter_Type: "Integer", UOM: "", rowId: "2"}] const newDataString = `[[Row_id: "32F993F", Parameter_Type: "String", UOM: "", rowId: "1"],[Row_id: "88898897-988D-4168-B662-2DECEA0E72BD", Parameter: "id", Parameter_Type: "Integer", UOM: "", rowId: "2"]]` const newDataR = JSON.parse(newDataString .replace('[[','[{') .replace(']]','}]') .replace('],[','},{') .replace(/(\\w+): /g,'"$1":') ); console.log(newDataR) console.log(JSON.stringify(oldData) === JSON.stringify(newDataR))

您可以將兩者都轉換為字符串並使用正則表達式將 '{' 和 '}' 替換為 '[' 和 ']'。

 let oldData = '[{Row_id: "32F993F", Parameter_Type: "String", UOM: "", rowId: "1"},{Row_id: "88898897-988D-4168-B662-2DECEA0E72BD", Parameter: "id", Parameter_Type: "Integer", UOM: "", rowId: "2"}]' let newData = '[[Row_id: "32F993F", Parameter_Type: "String", UOM: "", rowId: "1"],[Row_id: "88898897-988D-4168-B662-2DECEA0E72BD", Parameter: "id", Parameter_Type: "Integer", UOM: "", rowId: "2"]]' oldData = oldData.replace(/[{]/g, '['); oldData = oldData.replace(/[}]/g, ']'); console.log(oldData === newData);

暫無
暫無

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

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