【问题标题】:How can get only key values from the join() values in javascript?如何从 javascript 中的 join() 值中仅获取键值?
【发布时间】:2018-08-03 06:36:34
【问题描述】:
const myQuestions =  [
        {
                level:"Level 1",
                questionNo: 1,
                sentence: "Her uncles are army officers.",
                question: "Q . Which words are about people? ",
                answers: {
                    "1": "a. uncles / officers",
                    "2": "b. her/are",
                    "3": "c. in/the"
                },
                correctAnswer: "1",
                topic: "Noun",
                description: "plural nouns"
            },
            {
                level:"Level 1",
                questionNo: 2,
                sentence: "He dropped the glass and it broke into many pieces.",
                question: "Q . Which word stands for 'the glass'?",
                answers: {
                    "1": "a. he",
                    "2": "b. it",
                    "3": "c. into"
                },
                correctAnswer: "2",
                topic: "Pronoun",
                description: "pronoun  'it' and what it has already referred to"
            },
     ....
     ]

这是我的 JSON。下面是我的 Html5 代码

<div class="answers"> ${answers.join("")} </div>

现在我们也得到了这样的键和值。

1:一个。叔叔/军官

但我们只想要值。谁能解决这个问题?

【问题讨论】:

  • 什么是answers?
  • 你是如何从myQuestions[i].answers 创建answers 的?
  • 使用Object.values(myQuestions[i].answers) 获取值。

标签: javascript json node.js html


【解决方案1】:

您可以为此使用Object.values():

${Object.values(answers).join("")}

const myQuestions = [{
  level: "Level 1",
  questionNo: 1,
  sentence: "Her uncles are army officers.",
  question: "Q . Which words are about people? ",
  answers: {
    "1": "a. uncles / officers",
    "2": "b. her/are",
    "3": "c. in/the"
  },
  correctAnswer: "1",
  topic: "Noun",
  description: "plural nouns"
}];

console.log(Object.values(myQuestions[0].answers).join(', '));

【讨论】:

  • 我得到了同样的结果
  • 没找到你。输出是什么?和你帖子里的一样吗?
  • 它的工作。但我没有数组。我们能做什么?
  • n 个数组 的问题或答案?
  • 是的,它包含 n 个问题或答案数组
【解决方案2】:

当你这样做时:

answers.join("")

然后将join 方法应用于整个answers 对象,并将其键和值连接起来。

为了只将值提供给join,请执行以下操作:

Object.values(answers).join("")

更具体地说:

var answers = myQuestions[0].answers;
console.log(Object.values(answers).join(""));

(如this codepen所示)。

【讨论】:

  • 但我得到相同的结果
【解决方案3】:

const myQuestions = [{
  level: "Level 1",
  questionNo: 1,
  sentence: "Her uncles are army officers.",
  question: "Q . Which words are about people? ",
  answers: {
    "1": "a. uncles / officers",
    "2": "b. her/are",
    "3": "c. in/the"
  },
  correctAnswer: "1",
  topic: "Noun",
  description: "plural nouns"
}]


const ans = Object.values(myQuestions[0].answers)

console.log(ans)

【讨论】:

  • 这就够了吗?
猜你喜欢
  • 2018-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-10
  • 2021-07-22
  • 2019-08-07
  • 1970-01-01
相关资源
最近更新 更多