在对象内映射数组

时间:2017-03-10 20:31:26

标签: javascript lodash

我有以下复杂的JSON对象,它在数组中有数组和数组。如何解析这些数组并为数组中的每个元素创建一个对象数组。我在我的项目中使用了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 
     }]
}
]

2 个答案:

答案 0 :(得分:2)

您可以使用omit获取没有details数组的学生的subjects,使用这些details使用{{3}转换主题数组中的每个项目通过defaults

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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我鼓励您使用Normalizr包。它非常有用,即使它们是嵌套的,也会非常关注你的收藏。