首页 > 解决方案 > 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 转换为有效数据?谢谢。

标签: javascriptobjectmultidimensional-arraylodashjavascript-objects

解决方案


仅当 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))


推荐阅读