javascript - 有没有比我在这里写的更好的方法来比较两个具有不同键的对象?
问题描述
基本上我正在尝试比较 javascript 中具有不同键名的两个对象,但我想将 theobjectToSync
的值与mainObject
. 有些值有不同的类型,有些是嵌套的。我尝试使用 array.reduce 方法,但它很快变成了意大利面。
但我现在拥有的是:
// Check data between two objects and return an object
// with only data from the 'mainObject' if it doesn't match
const categories = [{
id: 21,
syncToId: 2
}]
const objectToSync = {
id: 44,
status: 'publish',
name: 'test product',
price: '1.99000000',
stock_quantity: 0,
categories: 21,
meta_data: [{
key: 'productid',
value: '226'
}, {
key: 'irrelevant data',
value: 'meow'
}]
}
const mainObject = {
id: 226,
status: 'ACTIVE',
name: {
en: 'Test Product Updated'
},
price: 2.99,
quantity_in_stock: 5,
group_id: 2,
}
// Use Map?
let check = new Map([
['same', (sync, main, type) => {
const result = sync == main ? undefined : main.type
return type == 'string' ? String(main) : main
}],
['status', (sync, main) => {
const status = main == 'ACTIVE' ? 'publish' : 'draft';
if (sync == status) {
return
} else {
return status
}
}]
]);
// if it returns undefined, it means it's still the same and we don't need to change it
const newObject = {
id: check.get('same')(objectToSync.meta_data.find(x => x.key =='productid').value, mainObject.id),
name: check.get('same')(objectToSync.name, mainObject.name.en,),
price: check.get('same')(+objectToSync.price, mainObject.price, 'string'),
status: check.get('status')(objectToSync.status, mainObject.status),
// etc
}
// Now Remove 'undefined' values from newObject
Object.keys(newObject).forEach(key => newObject[key] === undefined ? delete newObject[key] : {});
console.log(newObject);
对于像我这样的初学者来说,有没有更实用的方法可以轻松阅读?
主要原因是因为我从一个 API 下载大量产品数据集并将它们保存到 JSON 文件,然后我也将我的 WooCommerce 产品下载到 JSON 文件,然后将 API 产品与我的 WooCommerce 产品进行比较确保它们仍然匹配。无论我不发送到 WC rest api 以进行更新。
解决方案
推荐阅读
- apache-kafka - 如何在 Select 语句中选择记录的键
- angular - Router.Navigate 不调用组件中的服务
- java - 快速编辑私有变量
- sql - SQL 窗口函数 - 无法分组后如何处理
- ios - swift 4中datePicker中月份列中的随机值
- javascript - 如何以角度实现 bulma-calendar js 事件功能?
- asp.net-mvc - 解析 API 响应时遇到意外字符
- javascript - 反应原生 ListItem 图像 url 传递变量
- docker - 在树莓派上的 docker 容器中运行 firefox
- android - 创建无障碍服务以授予/撤销 android 手机上可用的其他应用程序的权限