我将如何使用下划线 js 将嵌套的 json 转换为展平的 json

问题描述

{ "data": [ { "appointment": "string","archived": true,"clinical-sections": [ { "clinical-template": 0,"name": "string","values": [ { "clinical-field": 0,"id": 0,"value": "string" } ] } ] } ] }

这是 json 响应,我的目标是使用下划线 js 将 /flatten 这个 json 转换为 flatten json 对象。

Desire 输出应该是这样的

{
  "data": [
    {
      "appointment": "string","clinical_note_template": 0,"clinical_note_field": 0,"value": "string"
    
  ]
}
 var result = []; 
   _.each(response.data,function(element) { _.each(clinical_note_sections,function(aitem) { var bitem = _.extend({ appointment: element.appointment },aitem); result.push(bitem); }); });
   return result;

The above function should return

{
  "data": [
{
"appointment": "string","clinical-note-template": 0
}
]
}

But It is not working and I have no idea hot to get the desire resut

解决方法

虽然你可以像这样使用适当的参数解构来做一些事情:

const convert = ({data,...rest}) => ({
  ...rest,data: data.map(({
    appointment,archived,['clinical-sections']: [{
      ['clinical-template']: clinical_note_template,name,values: [{
        ['clinical-field']: clinical_note_field,id,value
      }]
    }]
  }) => ({appointment,clinical_note_template,clinical_note_field,value}))
})


const response = {data: [{appointment: "string",archived: true,"clinical-sections": [{"clinical-template": 0,name: "string",values: [{"clinical-field": 0,id: 0,value: "string"}]}]}]}

console .log (
  convert (response)
)
.as-console-wrapper {max-height: 100% !important; top: 0}

我怀疑发生的事情比我们目前看到的要多。

如果 clinical-sections 数组中有多个元素会怎样?那里面的 values 数组怎么样?哪些值会成为您的 clinical_note_templateclinical_note_field

但无论如何,这可能是一个开始。