首页 > 解决方案 > 有没有比我在这里写的更好的方法来比较两个具有不同键的对象?

问题描述

基本上我正在尝试比较 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 以进行更新。

标签: javascriptnode.jsarraysobjectcomparison

解决方案


推荐阅读