gpt4 book ai didi

javascript - 映射对象内的数组

转载 作者:行者123 更新时间:2023-12-01 03:55:31 25 4
gpt4 key购买 nike

我有以下复杂的 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
}]
}
]

最佳答案

您可以使用omit要在没有 subjects 数组的情况下获取学生的详细信息,请使用这些details 来使用 defaults 转换主题数组中的每一项。通过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>

关于javascript - 映射对象内的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42727211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com