I have below two objects and i need to compare values object with points object based on the given answer like ‘Q1A1’ or ‘Q2A1’ and once key match in both object then it should return the sum of their respective answers.
const values = {
Q1: {
Q1A1: "Yes",
},
Q2: {
Q2A1: "Yes",
},
Q3: {
Q3A2: "No",
},
};
const points = {
Q1A1: 41,
Q1A2: 0,
Q2A1: 19,
Q2A2: 0,
Q3A1: 25,
Q3A2: 0,
};
After comparing both above object based on the given answer the sum will be 60. So, how can i return the sum 60 by comparing these object ?
>Solution :
Use the values to drive the script:
const total = Object.values(values)
.reduce((acc, cur) => acc + Object.entries(cur)
.reduce((accInner, [key, val]) => val !== 'No' && points[key] ? accInner + points[key] : accInner
, 0)
, 0);
console.log(total)
<script>
const values = {
Q1: {
Q1A1: "Yes",
},
Q2: {
Q2A1: "Yes",
},
Q3: {
Q3A2: "No",
},
};
const points = {
Q1A1: 41,
Q1A2: 0,
Q2A1: 19,
Q2A2: 0,
Q3A1: 25,
Q3A2: 5, // should not be counted
};
</script>
Or (easier to read) make a lookup table and filter+reduce
const lookup = Object.values(values).reduce((acc, cur) => {
const [key, val] = Object.entries(cur)[0]
if (val === "Yes") acc[key] = val;
return acc;
}, {})
console.log(lookup)
const val = Object.entries(points)
.filter(entry => lookup[entry[0]] && entry[1])
.reduce((a, b) => a[1] + b[1]);
console.log(val)
<script>
const values = {
Q1: {
Q1A1: "Yes",
},
Q2: {
Q2A1: "Yes",
},
Q3: {
Q3A2: "No",
},
};
const points = {
Q1A1: 41,
Q1A2: 0,
Q2A1: 19,
Q2A2: 0,
Q3A1: 25,
Q3A2: 5, // should not be counted
};
</script>