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

时间:2015-12-23 22:15:58

标签: 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"}]

5 个答案:

答案 0 :(得分:4)

您可以使用JavaScript地图功能(假设变量q包含您的问题对象):

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

答案 1 :(得分:0)

假设问题ID和答案都在问题对象中,那么你可以按如下方式进行:

var answers = [];

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

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

答案 2 :(得分:0)

这里是你的json

SecondFrame

现在迭代它并创建一个新的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"] 
    }
  }
 ]}

答案 3 :(得分:0)

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。所以这没问题。

答案 4 :(得分:0)

这会将您的原始JSON映射到指定的JSON。使用reviver函数。

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);