Basically I'm trying to compare two objects in javascript that have different key names, but I want to match the values of the the objectToSync
with the values of the mainObject
. Some of the values have different types and some are nested. I tried to use array.reduce method but it quickly turned spaghetti.
But what I have now is this:
// 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);
Is there a more practical way of doing this that is easy to read for a beginner like me?
The main reason is because I'm downloading a large data set of products from one API and saving them to a JSON file, then I download my WooCommerce products to a JSON file as well and then compare the API products with my WooCommerce products to make sure they still match. Whatever doesn't I send to WC rest api to update.