javascript - 创建一个新的 JSON 数组,其中包含来自另一个 JSON 的特定属性

标签 javascript json

我有这个 JSON 对象数组

  "questions": [
  {
    "id": "id",
    "answer":"answer",
    "question_type": "q_type",
    "question": {
      "header":"Text",
      "question_image": "link", 
      "answers_list": ["array"],
    }
  },
  {
    "id": "id",
    "answer":"answer",
    "question_type": "q_type",
    "question": {
      "header": "Text",
      "question_image": "link",
      "choices_type": "text",
      "choices": ["array"] 
    }
  }
 ]

我想从这个 json 中提取另一个包含 id 和答案的 json,就像这样

"answers": [{"question": question_id, "answer": "text"}]

最佳答案

您可以使用 JavaScript 映射函数(假设变量 q 包含您的问题对象):

var out = q.questions.map(function(element) {
              return {"question": element.id, "answer": element.answer};
          });

关于javascript - 创建一个新的 JSON 数组,其中包含来自另一个 JSON 的特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34444563/

相关文章:

javascript - 表单验证失败后如何显示模式?

javascript - 减少第三方代码的影响(zendesk)

c# - 将反序列化的动态 Json 转换为强类型类

json - logstash 提取 json 字段并覆盖索引

c# - 如何为下面的 json 对象创建 c# 类?

javascript - 什么更快 : try catch vs Promise

javascript - 在 TypeScript 中,如何将属性添加到接口(interface)中的对象类型?

javascript - 如何禁用grails插件的资源

android - GSON 解析 Array in array in array

javascript - 为什么我们需要在 eval JSON 中添加括号?