首页 > 解决方案 > 比较具有相同属性的两个对象,但它混合在一起不遵循字母规则

问题描述

如果我有两个对象:

const a = {
   sample: 'this is sample',
   errorMessage: 'status is error'
}

const b = {
   errorMessage: 'status is error'
   sample: 'this is sample',
}

我知道如何通过对象的排序键对属性进行排序,但知道如何将其解析为对象。

例子:

const sortA = JSON.stringify(Object.keys(a).sort) 
const sortB = JSON.stringify(Object.keys(b).sort)

expected(sortA).toEquals(sortB)

标签: javascriptangularunit-testing

解决方案


您可以获取对象的条目,按键排序,获取 JSON 并比较字符串。

这仅适用于非嵌套对象。

const
    sortBy = k => (a, b) => a[k].localeCompare(b[k]),
    a = { sample: 'this is sample', errorMessage: 'status is error' },
    b = { errorMessage: 'status is error', sample: 'this is sample' },
    sortA = JSON.stringify(Object.entries(a).sort(sortBy(0))),
    sortB = JSON.stringify(Object.entries(b).sort(sortBy(0)));

console.log(sortA === sortB);


推荐阅读