[英]Map array inside an object
我有以下復雜的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
}]
}
]
您可以使用省略來獲取沒有subjects
數組的學生的details
,使用這些details
通過map使用默認值來轉換主體數組中的每個項目。
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>
我鼓勵您使用Normalizr軟件包。 這非常有用,即使您的收藏是嵌套的,也能照顧到您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.