繁体   English   中英

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

[英]Create a new JSON array that contain specific properties from another 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 map函数(假设变量q包含您的问题对象):

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

假设问题ID和答案都在问题对象中,则可以按照以下步骤进行操作:

var answers = [];

for(var i = 0; i < questions.length; i++)
{
    answers.push({
        question: questions[i].id,
        answer: questions[i].answer
    });
}

这也假设您将问题数组声明为var questions = ...

这是你的json

var json = {"questions": [
  {
    "id": "id",
    "answe":"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对象

var answers = []
var question = {}

json.questions.forEach(function(value, index){
    question.id = value.id;
    question.answer = value.answer;
    answers.push(question);

});

var resultJson = {};

resultJson.answers = answers;
var answers = questions.reduce(function (result, question){
    return result.concat(item.question.answers_list.map(function (answer) {
        return {
            question: {
                id: question.id
            },
            answer: answer
        }
    }));
}, []);

您需要“映射”问题的数据,因为如果要将其解析为JSON,则需要小心循环引用。 但是,您只需要指定question.id即可。 所以没问题。

这会将您的原始JSON映射到指定的JSON。 使用齐磊功能。

 var 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"]}}]}'; var keep = ['', 'questions', 'id', 'answer']; var newJson = JSON.stringify(JSON.parse(json, function(k, v) { var idx = k && k == +k; if (idx || keep.indexOf(k) > -1) { if (idx && typeof v === 'object') { var id = v.id; delete v.id; v.question = id; } return v; } })); document.body.textContent = newJson; console.log(newJson); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM