javascript - 比较具有相同属性的两个对象,但它混合在一起不遵循字母规则
问题描述
如果我有两个对象:
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)
解决方案
您可以获取对象的条目,按键排序,获取 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);
推荐阅读
- python - 将数字字符串转换为数字列表
- javascript - 渲染整个文档时,React 和 PDF.js 更改页面不起作用
- javascript - 在函数之外重用变量时遇到问题
- azure - Microsoft Graph API - 如何更新 userSMIMECertificate
- python - Cassandra在一列中导入JSON
- python-3.x - Scrapy蜘蛛没有访问我想要的链接
- php - 无法从文件中获取 wordpress 网站
- php - PHP 渲染 html 表格的时间太长
- python - 周日日期插补
- ffmpeg - 为什么 ffmpeg C - API Doxygen 文档使用 c++ 风格的命名空间进行结构