我有一个深层嵌套的对象,其中包含对象和对象数组。我想将此对象平整为单个级别的对象,但遇到了麻烦。我使用此功能:
function flat(r, a) {
var b = {};
Object.keys(a).forEach(function (k) {
if (k !== 'children') {
b[k] = a[k];
}
});
r.push(b);
if (Array.isArray(a.children)) {
b.children = a.children.map(function (a) { return a.name; });
return a.children.reduce(flat, r);
}
return r;
}
我要展平的对象是这样:
payment: {
keywords: [],
userCategories: [
{
userCategory: 'CORPORATE',
enabled: false
},
{
userCategory: 'RETAIL',
enabled: false
}
],
paymentDetailsType: 'DIAS',
billPaymentModels: [
{
contractType: 'RI18',
exists: false,
contracts: [
{
field: 'amount',
fieldType: 'amount',
name: [
{
localeLang: 'el',
value: 'ΠΟΣΟ'
},
{
localeLang: 'en',
value: 'AMOUNT'
}
],
maxLength: 0,
index: 0,
editable: true
},
{
field: 'contract1',
fieldType: 'string',
isPaymentCode: true,
name: [
{
localeLang: 'el',
value: 'ΚΩΔΙΚΟΣ ΠΛΗΡΩΜΗΣ'
},
{
localeLang: 'en',
value: 'PAYMENT CODE'
}
],
maxLength: 25,
index: 2
},
{
field: 'debtorName',
fieldType: 'string',
name: [
{
localeLang: 'el',
value: 'ΟΝΟΜΑΤΕΠΩΝΥΜΟ/ΕΠΩΝΥΜΙΑ ΥΠΟΧΡΕΟΥ'
},
{
localeLang: 'en',
value: 'DEBTOR NAME'
}
],
maxLength: 70,
index: 3,
formats: [
{
type: 'FULLNAME'
}
]
}
],
validations: [
{
errorMessage: [
{
localeLang: 'el',
value: 'Υποχρεωτικό πεδίο'
},
{
localeLang: 'en',
value: 'Required field'
}
],
validationType: 'REQUIRED',
parameters: {
field: 'contract1'
},
scope: 'FIELD'
},
{
errorMessage: [
{
localeLang: 'el',
value: 'Υποχρεωτικό πεδίο'
},
{
localeLang: 'en',
value: 'Required field'
}
],
validationType: 'REQUIRED',
parameters: {
field: 'amount'
},
scope: 'FIELD'
},
{
errorMessage: [
{
localeLang: 'el',
value: 'Παρακαλώ εισάγετε έγκυρο Κωδικό Πληρωμής'
},
{
localeLang: 'en',
value: 'Please enter a valid Bank Payment Code'
}
],
validationType: 'RI18',
scope: 'FIELD'
}
]
}
],
channelAttributes: [
{
subChannel: null,
active: true,
name: [
{
localeLang: 'el',
value: ''
},
{
localeLang: 'en',
value: ''
}
]
}
],
}
问题是密钥应该是这样的: payment.billPaymentsModel [0] .contracts [0] .name,但输出为payment.billPaymentsModel.0.contracts.0.name