合并两个嵌套的JSON数组

时间:2016-04-12 01:22:36

标签: javascript json node.js

我正在使用从JSON模式动态构建的表单,如下所示:

{
  "questionSets": [
    {
      "questionSetId": "example-fields",
      "questions": [
        {
          "questionId": "text",
          "question": "Text Field",
          "input": {
            "type": "textInput",
            "default": ""
          },
        },
        {
          "questionId": "textarea",
          "question": "Text Area",
          "input": {
            "type": "textareaInput",
            "default": ""
          }
        }
      ]
    }
  ]
}

提交表单时,它只返回如下所示的更新值:

{
  text: "some entered text", 
  textarea: "some more entered text"
}

此生成的JSON数组的键与 questionId 以及第一个数组中带有默认键的值相对应。

合并这两个数组的最佳方法是什么,结果是:

{
  "questionSets": [
    {
      "questionSetId": "example-fields",
      "questions": [
        {
          "questionId": "text",
          "question": "Text Field",
          "input": {
            "type": "textInput",
            "default": "some entered text"
          },
        },
        {
          "questionId": "textarea",
          "question": "Text Area",
          "input": {
            "type": "textareaInput",
            "default": "some more entered text"
          }
        }
      ]
    }
  ]
}

1 个答案:

答案 0 :(得分:2)

这是一个棘手的问题。最简单的方法是使用underscore。让reply成为您的输入对象,defaultInputs具有默认输入的对象将在JSON中填写。

'use strict';

let _ = require('underscore');

module.exports = function (defaultInputs, reply) {

    reply.questionSets = _.map(reply.questionSets, questionSet => {
        questionSet.questions = _.map(questionSet.questions, question => {
            question.input.default = _.find(defaultInputs,(item, key) => (
                new RegExp(`${key}Input`).test(question.input.type) && item
            ) || false) || '';

            return question;
        });
        return questionSet;
    });

    return reply;
};

可以找到正确的代码解决方案(包括测试)here

更新(07/01/2018)

现在可以通过新的数组原型函数实现相同的功能,例如mapfilter

'use strict';

module.exports = function (defaultInputs, reply) {

    reply.questionSets = reply.questionSets.map(questionSet => {
        questionSet.questions = questionSet.questions.map(question => {
            question.input.default = defaultInputs.filter((item, key) => (
                new RegExp(`${key}Input`).test(question.input.type) && item
            ) || false) || '';

            return question;
        });
        return questionSet;
    });

    return reply;
};