与字典元素打字稿比较

时间:2018-12-20 08:59:21

标签: javascript typescript dictionary compare

我有这样的模型:

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} 我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

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);
});

答案 1 :(得分:0)

如果只有数字,字符串,对象和数组,则只需

JSON.stringify(originalValues)==JSON.stringify(values);