I want to create a new object.
An object that adds only values of the same key.
I want to make it in a way that adds num1 to each other and num2 to num2.
The created object has a value of num1 : 4.
But I don't know why the value is NaN
this is my code.
let mydata = [
{num1: 1 , num2: 2 , num3: 3, num4: 4},
{num1: 1 , num2: 2 , num3: 3, num4: 4},
{num1: 1 , num2: 2 , num3: 3, num4: 4},
{num1: 1 , num2: 2 , num3: 3, num4: 4},
]
const sum = {};
for(let prop of mydata){
for(let key in prop){
sum[key] = prop[key];
}
}
console.log(sum);
//{ num1: NaN, num2: NaN, num3: NaN, num4: NaN } => why Nan??
CodePudding user response:
sum[key]
default value is undefined
, undefined
a number = NaN, so you need to assign 0 for sum[key]
initially
let mydata = [{
num1: 1,
num2: 2,
num3: 3,
num4: 4
},
{
num1: 1,
num2: 2,
num3: 3,
num4: 4
},
{
num1: 1,
num2: 2,
num3: 3,
num4: 4
},
{
num1: 1,
num2: 2,
num3: 3,
num4: 4
},
]
const sum = {};
for (let prop of mydata) {
for (let key in prop) {
if (!sum[key]) {
sum[key] = 0;
}
sum[key] = prop[key];
}
}
console.log(sum);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
CodePudding user response:
sum[key]
is initially undefined
, and undefined
number
yields NaN
.
You can fix this by assigning a value of zero to sum[key]
if its value is falsy:
for(let prop of mydata) {
for(let key in prop) {
sum[key] = sum[key] || 0;
sum[key] = prop[key];
}
}
Or if you want to condense things further:
for(let prop of mydata) {
for(let key in prop) {
sum[key] = (sum[key] || 0) prop[key];
}
}