我有以下复杂的JSON对象,该对象在一个数组内有一个array和一个array。如何解析这些数组并为数组中的每个元素创建一个对象数组。我在项目中使用lodash库,以防万一有可用的功能。

   {
  studentId: 123
  name: XYZ
  phone: 34234234
  gender: M
  subjects: [{
     studentId: 123
     subjectName: Math
     scores:50
    assignments:[
     {
        type: Internal,
        submitted: yes,
        status: failed
     },
     {
        type: External,
        submitted: yes,
        status: passed
     }]
},
{
     studentId: 123
     subjectName: Science
     score: 20
     assignments:[
     {
        type: Internal,
        submitted: yes,
        status: passed
     },
     {
        type: External,
        submitted: yes,
        status: failed
     }]
}]

}


期望:

[{
  studentId:123,
  name: XYZ
  phone: 34234234
  gender: M,
  subjectName: Math
  scores:50
  assignments:[
     {
        type: Internal,
        submitted: yes,
        status: failed
     },
     {
        type: External,
        submitted: yes,
        status: passed
     }]
},
{
 studentId:123,
  name: XYZ
  phone: 34234234
  gender: M,
  subjectName: science
  scores:20
  assignments:[
     {
        type: Internal,
        submitted: yes,
        status: failed
     },
     {
        type: External,
        submitted: yes,
        status: passed
     }]
}
]

最佳答案

您可以使用omit来获取不带details数组的学生的subjects,使用这些details来使用defaultsmap变换主题数组中的每个项目。

var details = _.omit(data, 'subjects');
var result = _.map(data.subjects, function(subject) {
  return _.defaults({}, details, subject);
});




var data = {
    studentId: '123',
    name: 'XYZ',
    phone: '34234234',
    gender: 'M',
    subjects: [{
        studentId: '123',
        subjectName: 'Math',
        scores: 50,
        assignments: [{
            type: 'Internal',
            submitted: 'yes',
            status: 'failed'
          },
          {
            type: 'External',
            submitted: 'yes',
            status: 'passed'
          }
        ]
      },
      {
        studentId: '123',
        subjectName: 'Science',
        score: 20,
        assignments: [{
            type: 'Internal',
            submitted: 'yes',
            status: 'passed'
          },
          {
            type: 'External',
            submitted: 'yes',
            status: 'failed'
          }
        ]
      }
    ]
};

var details = _.omit(data, 'subjects');
var result = _.map(data.subjects, function(subject) {
  return _.defaults({}, details, subject);
});

console.log(result);

body > div { min-height: 100%; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

10-04 22:33
查看更多