【问题标题】:Merging two nested JSON arrays合并两个嵌套的 JSON 数组
【发布时间】:2018-01-08 09:37:48
【问题描述】:

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

{
  "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 数组的键对应于第一个数组中的 questionIddefault 键的值。

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

{
  "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"
          }
        }
      ]
    }
  ]
}

【问题讨论】:

  • 也许可以创建一个创建空数组的函数,并遍历结果并相应地附加到空数组?

标签: javascript json node.js


【解决方案1】:

这是一个棘手的问题。最简单的方法是使用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找到合适的代码解决方案(包括测试)。


更新(2018 年 7 月 1 日)

现在可以通过 mapfilter 等新的 Array 原型函数实现相同的目标

'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;
};

【讨论】:

    猜你喜欢
    • 2017-08-24
    • 2012-09-20
    • 2017-12-07
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2019-05-26
    相关资源
    最近更新 更多