[英]Javascript : Return Unmatched value from multidimensional arrays that contains object
[英]Javascript compare two JSON arrays and return key of the unmatched value
我有两个 JSON arrays,想知道不匹配的密钥。 我不需要价值。
例子:
livetable: [
{ id: 1, name: "Sandra" },
{ id: 2, name: "John" },
],
backupTable: [
{ id: 1, name: "Sandra" },
{ id: 2, name: "Peter" },
],
我可以得到与这个 Lodash 脚本不同的键/值对:
difference = _.differenceWith(livetable,backupTable,_.isEqual)
但我只需要密钥,在此示例中,“id: 2”的“名称”不匹配,因此我需要获取新数组/变量的“名称”密钥。
(使用 VUE CLI)
编辑:添加了当前代码 output 的示例。
var livetable = [{"id": 1, "name": "Sandra", "id": 2, "name": "John"}] var backupTable = [{"id": 1, "name": "Sandra", "id": 2, "name": "Peter"}] console.log(_.differenceWith(backupTable,livetable,_.isEqual))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
这将 output 键:值对,但我只需要不同的键。
我想我明白你想要做什么。 但是有一些未知数,例如如果第二个数据集中缺少记录会发生什么?
此解决方案假设每个数据表具有相同数量的记录并且记录具有相同的 ID。
// define data
const livetable = [
{ id: 1, name: "Sandra" },
{ id: 2, name: "John" }
]
const backupTable = [
{ id: 1, name: "Sandra" },
{ id: 2, name: "Peter" }
]
const getDifferentRecordsByID = (sourceRecords, compareRecords) => {
// simple utility function to return a record object matching by ID
const findComparisionRecord = id => compareRecords.find(compareRecord => compareRecord.id === id)
// using the utility function, we can filter out any mismatching records by comparing name
return sourceRecords
.filter(sourceRecord => sourceRecord.name !== findComparisionRecord(sourceRecord.id).name)
// then map over all the records and just pull out the ID
.map(record => record.id)
}
console.log(getDifferentRecordsByID(livetable, backupTable)) // [2]
这是解决我的问题的 VUE 代码。 Function 返回[ "name" ]
,这正是我所需要的。
data() {
return {
livetable: [{ id: 1, name: "Sandra" },{ id: 2, name: "John" }],
backupTable: [{ id: 1, name: "Sandra" },{ id: 2, name: "Peter" }],
difColumns: null,
};
},
methods: {
test3() {
let resultArray = []
this.livetable.forEach((array1, index) => {
const array2 = this.backupTable[index];
resultArray.push(this._.reduce(array1, (result, value, key) => this._.isEqual(value, array2[key]) ? result : result.concat(key), []))
});
this.difColumns = resultArray[0]
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.