I have below sample data array of object and submittedValue object. The data array of object is constant it won’t change but submitttedValue
object will change as user proceed with the answer. I have put below desired result need to extract from data array of object and submittedValue object. Please help me out if you have any solution for this.
const data = [{
id: "Q1",
state: "Test 1",
answers: [
{ id: "Q1A1", text: "Yes" },
{ id: "Q1A2", text: "No" },
],
}, {
id: "Q2",
state: "Test 2",
answers: [
{ id: "Q2A1", text: "Yes" },
{ id: "Q2A2", text: "No" },
],
}];
const submittedValue = {
Q1: {
Q1A1: "Yes",
},
Q2: {
Q2A2: "No",
},
};
How do I get the below desired result by comparing above data array of object with submittedValue object ?
// Expected outcome
const result = [
{ state: "Test 1", answer: "Yes" },
{ state: "Test 2", answer: "No" },
];
3
Answers
If entries of
submittedValue
are guaranteed to have exactly 1 property with the answer, you can access it by simply usingObject.values(submittedValue[id])[0]
.From the provided data structure, …
… the submitted value …
… and the expected result …
… it is obvious that one needs the
data
just for looking up the test name which is a data-item’sstate
-value and becomes a result-item’sstate
-value as well …const result = [ { state: 'Test 1', ... }, ... ];
.As for any result-item’s
answer
-value, it has to be extracted from each related submitted value’s single nested property, because in the latter lays the truth and not within thedata
structure.Thus, in order to come up with the most efficient approach for retrieving any submitted value’s test name, one does
reduce
thedata
array into an object-based lookup-table where one maps itsstate
/test-name by itsid
where the latter is the key and the former is the value … e.g. …The final result then just needs to be
map
ped from thesubmittedValue
‘sentries
array, where each entry-key relates to the result’sstate
/test-name value and each entry-value is an object with just a single own property. The property name does not matter for the result-item’sanswer
-value will always be the first item of the object’svalues
array.Thus an efficient solution can be based on a single
reduce
task for creating the lookup and another singlemap
task which already creates the final result …