im trying to iterate over an Object which has lots of smaller objects inside it. I want to conditionally insert a key value pair in each of those smaller objects For Example :
const answers = {
"question1": {
answer: "Poor",
metric: "focus"
},
"question2": {
answer: {agree: "yes", duration: "10"}
metric: "exercise"
}
}
so lets say the answer in question1 can either be poor, good or excellent with poor being equal to a score of 1, good a score of 5 and excellent a score of 10. Depending on the answer in question1 i would like to add a key value pair like score: 1 into the question1 object
Then for question2 we look at the duration and a duration of 10 gives us a score of 10 so we insert the key value pair like score: 10
So in the end i want to return an object that looks something like:
newAnswers = {
"question1": {
answer: "Poor",
metric: "focus",
score: 1
},
"question2": {
answer: {agree: "yes", duration: "10"}
metric: "exercise",
score: 10
}
}
In this example im showing just two questions for simplicity, but in reality it could be many, and the same logic will apply to all the other questions.
Thanks in advance
CodePudding user response:
Basically what you need is a looping logic
Somthing like this will help.
Logic
- Loop through the entries in the object
- Check the type of
answer
key in each object - If type is a string do mapping between
"poor", "good", "excellent"
options. - If its object check validity of
duration
and assign it to the score.
Working Fiddle
const answers = {
"question1": {
answer: "Poor",
metric: "focus"
},
"question2": {
answer: {agree: "yes", duration: "10"},
metric: "exercise"
}
};
Object.entries(answers).forEach((item) => {
const answer = item[1].answer;
switch (typeof answer) {
case "string":
console.log(answer);
const answerOptions = ["poor", "good", "excellent"];
const scoreOptions = [1, 5, 10];
const index = answerOptions.indexOf(answer.toLowerCase());
if(index !== -1) {
item[1].score = scoreOptions[index];
}
break;
case "object":
if (answer.duration && !isNaN(answer.duration)) {
item[1].score = answer.duration;
}
break;
}
});
console.log(answers)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
If I understand your question correctly, the question is how to insert a new attribute for each JSON object. If it is the case, you can do as follow.
answers["question1"]["score"] = 1;
Neglecting the conditional checking your logic (i.e. the conditional statement), the iteration could be:
$.each(answers, (q) => {
q["score"] = x;
}