在 JSON 中插入键值对 (key & value),插入位置是没有答案的地方。

huangapple go评论80阅读模式
英文:

Insert the pair (key & value) into the json in the position where has no answer

问题

The result i want:

{"1": "b.) some pasta salad","2": " a.) some bread", "3":"*NOANSWER*","4":"*NOANSWER*","5": " a.) eggs and toast","6":"*NOANSWER*", "7":"*NOANSWER*"}
英文:

I'm working on a quiz-game and need to fill in the missing candidate's answer.

The total number of questions in the Quiz is 7.

The total number of questions that the candidate answered is 3

So need to add 4 corresponding elements in json. If the position is not available, write the value as NOANSWER

Json of candidate’s answer:

{"1": "b.) some pasta salad", "2": " a.) some bread", "5": " a.) eggs and toast" }

=> Insert key & value in position 3,4,6

The result i want:

{"1": "b.) some pasta salad","2": " a.) some bread", "3":"*NOANSWER*","4":"*NOANSWER*","5": " a.) eggs and toast","6":"*NOANSWER*", "7":"*NOANSWER*"}

Thank you

答案1

得分: 2

这里是一种方法:

const data = {
    1: "b.) 一些意面沙拉",
    2: "a.) 一些面包",
    5: "a.) 鸡蛋和土司",
};

const fillAnswers = (answers) => {
    const filled = {};
    for (let i = 1; i <= 7; i++) {
        filled[i] = answers[i] || "*无答案*";
    }

    return filled;
};

console.log(fillAnswers(data))
英文:

Here's an approach
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = {
    1: &quot;b.) some pasta salad&quot;,
    2: &quot; a.) some bread&quot;,
    5: &quot; a.) eggs and toast&quot;,
};

const fillAnswers = (answers) =&gt; {
    const filled = {};
    for (let i = 1; i &lt;= 7; i++) {
        filled[i] = answers[i] || &quot;*NOANSWER*&quot;;
    }

    return filled;
};

console.log(fillAnswers(data))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 18:10:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定