gpt4 book ai didi

javascript - 如何比较两个对象 typescript angular6

转载 作者:搜寻专家 更新时间:2023-10-30 22:04:28 25 4
gpt4 key购买 nike

我想比较两个 Json 对象数组。一个有更多的数据。对于最终结果,如果一个 id 找到另一个 selected checkbox = true。到目前为止有 4 个,它只找到一个。我是否首先循环遍历长数组,然后循环遍历第二个数组以找到匹配项?

 this.formAll = JSON.parse(response)
for (var i = 0; i < this.formAll.length; i++) {
for (var j = i; j < this.formAb.length; j++) {
console.log( this.formAb[j].id, this.formAll[i].SeriesNumber);
if ( this.formAll[i].id === this.formAb[j].id) {
console.log( 'small=', this.formAb[j].id, 'large=',
this.formAll[i].id );
this.formAll[i].selected = true;
}}
}

最佳答案

快速而有限

JSON.stringify(obj1) === JSON.stringify(obj2)

慢且更通用

Object.equals = function( x, y ) {
if ( x === y ) return true;
// if both x and y are null or undefined and exactly the same

if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
// if they are not strictly equal, they both need to be Objects

if ( x.constructor !== y.constructor ) return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.

for ( var p in x ) {
if ( ! x.hasOwnProperty( p ) ) continue;
// other properties were tested using x.constructor === y.constructor

if ( ! y.hasOwnProperty( p ) ) return false;
// allows to compare x[ p ] and y[ p ] when set to undefined

if ( x[ p ] === y[ p ] ) continue;
// if they have the same strict value or identity then they are equal

if ( typeof( x[ p ] ) !== "object" ) return false;
// Numbers, Strings, Functions, Booleans must be strictly equal

if ( ! Object.equals( x[ p ], y[ p ] ) ) return false;
// Objects and Arrays must be tested recursively
}

for ( p in y ) {
if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) return false;
// allows x[ p ] to be set to undefined
}
return true;
}

关于javascript - 如何比较两个对象 typescript angular6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52049872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com