This question already has answers here:
How to determine equality for two JavaScript objects?
                            
                                (62个答案)
                            
                    
                2年前关闭。
        

    

我有这样的模型:



class Model {
  from: number;
  values: { [id: string]: number };
  originalValues: { [id: string]: number };
}





然后我创建arr = Model[] = [];

我需要检查值是否匹配originalValues,这就是我的方法:

 for (let edited of this.arr) {
  edited.model.forEach(m => {
    if (Object.values(m.originalValues) == Object.values(m.values)) {
    // console.log(equal);
    } else {
      // not equal
    }
  });


但是即使它们相等,我也总是得到not equal
值和原始值的示例如下:
originalValues: {11c33aaaaaaaaasafsdf33: 23.5}
我在这里做错了什么?

最佳答案

const log = args => console.log(args);


const array = [{
  values: [1, 2, 3],
  otherValues: [1, 2, 3]
}, {
  values: [1, 2, 3],
  otherValues: [1, 2, 3, 'a', 'b', 'c']
}, {
  values: [1, 2, 3],
  otherValues: [3, 2, 1]
},{
  values: [{ name: 'Jack' }, 'a', 'b', 'c', 1, 2, 3],
  otherValues: [1, 2, 3, 'a', 'b', 'c', { name: 'Jack' }]
}];


log('\nOriginal');
array.forEach(o => {
  const bool = JSON.stringify(o.values) === JSON.stringify(o.otherValues);
  log(bool);
});


log('\nEdit');
array.forEach(o => {
  const v1 = Object.values(o.values).sort(), v2 = Object.values(o.otherValues).sort();
  const bool = JSON.stringify(v1) === JSON.stringify(v2);
  log(bool);
});

09-26 19:28