Reputation: 695
Supposed that I have two arrays to compare:
var arrOriginal={currency1: 1234, currency2: 2345};
var arrToCompare={currency1: 123};
I was trying to find the difference between the two.
Example result:
var result={currency1: 1111, currency2: 2345}
What I've tried:
Using for .. in
and then substract.
for (var key in this.arrOriginal) {
this.result.push({
currency: key,
amount: format.formatCurrency(this.arrToCompare[key] - this.arrOriginal[key])
});
}
But it won't show the currency key which the second array don't have.
Any help is appreciated.
Upvotes: 2
Views: 87
Reputation: 22360
A very easy to understand approach would be to have an if-else statement with three branches that check if the key exists in both or either one of the original objects:
const original = { currency1: 1234, currency2: 2345 }
const toCompare = { currency1: 123 }
const result = {}
const allKeys = new Set(Object.keys(original).concat(Object.keys(toCompare)))
allKeys.forEach(k => {
if (k in original && k in toCompare) {
result[k] = original[k] - toCompare[k]
} else if (k in original) {
result[k] = original[k]
} else {
result[k] = toCompare[k]
}
})
console.log(result)
Upvotes: 1
Reputation: 386560
You could take a default value of zero for undefined
properties of the object.
From inside to out:
Object.assign
.var original = { currency1: 1234, currency2: 2345 },
deltas = { currency1: 123 },
result = Object.assign(
{},
...Object.entries(original).map(([k, v]) => ({ [k]: v - (deltas[k] || 0)}))
);
console.log(result);
Upvotes: 4
Reputation: 37755
You can use Object.entries
and reduce
var arrOriginal={currency1: 1234, currency2: 2345};
var arrToCompare={currency1: 123};
let final = Object.entries(arrOriginal).reduce((op,[key,value])=>{
op[key] = value - (arrToCompare[key] || 0)
return op
},{})
console.log(final)
Upvotes: 1
Reputation: 4330
A very simple approach is looping over the keys of arrOriginal
, If that key is present in arrToCompare
then substract that value else do not substract.
var arrOriginal={currency1: 1234, currency2: 2345};
var arrToCompare={currency1: 123};
var out = {}
for(var key in arrOriginal){
out[key] = arrOriginal[key] - (arrToCompare[key] || 0)
}
console.log(out)
Upvotes: 3