2016-04-12 14 views
-2

Merging:Şöyle bir JSON şemasından JavaScript dinamik yapılı bir form ile çalışıyorum iç içe iki JSON diziler

formu sadece şuna benzer güncellenmiş değerleri döndürür gönderilirse
{ 
    "questionSets": [ 
    { 
     "questionSetId": "example-fields", 
     "questions": [ 
     { 
      "questionId": "text", 
      "question": "Text Field", 
      "input": { 
      "type": "textInput", 
      "default": "" 
      }, 
     }, 
     { 
      "questionId": "textarea", 
      "question": "Text Area", 
      "input": { 
      "type": "textareaInput", 
      "default": "" 
      } 
     } 
     ] 
    } 
    ] 
} 

Bu elde edilen JSON dizinin

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

anahtarlar QuestionID ve birinci dizideki varsayılan anahtarla değeri karşılık gelir. ilginç bir olay var

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

filter gibi yeni Dizi prototip fonksiyonları vasıtasıyla aynı elde etmek mümkündür boş bir dizi ve sonuçların üzerinden yineleyin ve buna göre boş diziye ekleyin? – argon

cevap

2

:

sonucudur bu yüzden bu 2 dizileri birleştirme hakkında gitmek için en iyi yolu nedir. En basit yol underscore kullanıyor. reply giriş nesnesini ve defaultInputs JSON'ta doldurulacak varsayılan girişleri olan nesneyi bırakın.

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

(testi de dahil olmak üzere) bir doğru kod çözümü here bulunabilir.


GÜNCELLEME (07/01/2018)

Şimdi Belki yaratan bir işlev yapmak map ve

'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; 
}; 
İlgili konular