我有一个带有子对象和数组的嵌套对象。像这样:
const documents = {
invoice: {
documentID: '_e4564',
displayName: '2019-02-03',
url: 'https://www.urltoinvoice.com'
},
conditions: {
documentID: '_e9365',
displayName: 'Conditions company x',
url: 'https://www.urltoconditions.com'
},
reminders: [
{
documentID: '_e4364',
displayName: 'First reminder',
url: 'https://www.urltofirstreminder.com'
},
{
documentID: '_e0254',
displayName: 'Second reminder',
url: 'https://www.urltosecondreminder.com'
},
]
}
我正在尝试创建一个新的对象数组以在选择框中使用。 子对象需要相同的属性,但具有基于文档类型的更新的displayName。因此,例如 reminder:首先提醒。
当前,这是我的代码:
const newArray = [];
this.addDocumentToArray(documents, newArray);
和addDocumentToArray函数:
addDocumentToArray = (documents, arr) => {
Object.entries(documents).forEach(([key, val]) => {
if (Array.isArray(val)) {
this.addDocumentToArray(val, arr);
} else {
arr.push({ documentID: val.documentID, displayName: `${key}: ${val.displayName}` });
}
});
}
这时的输出是一个看起来像这样的数组:
0: {documentID: "_e4564", displayName: "invoice: 2019-02-03"}
1: {documentID: "_e9365", displayName: "conditions: Conditions company x"}
2: {documentID: "_e4364", displayName: "0: First reminder"}
3: {documentID: "_e0254", displayName: "1: Second reminder"}
几乎可以,但是提醒的键是0
和1
。如何获得reminder
(或提醒)作为键?
答案 0 :(得分:2)
您可以向函数labelKey添加第三个可选参数。仅当您的值是数组时才传递该参数,它将在其他部分将其用作键
addDocumentToArray = (documents, arr, labelKey) => {
Object.entries(documents).forEach(([key, val]) => {
if (Array.isArray(val)) {
this.addDocumentToArray(val, arr, key);
} else {
arr.push({ documentID: val.documentID, displayName: `${labelKey || key}: ${val.displayName}` });
}
});
}
答案 1 :(得分:0)
我真的很喜欢克里斯的回答,所以我会尝试写一个替代方案:
let currentKey = null;
addDocumentToArray = (documents, arr) => {
Object.entries(documents).forEach(([key, val]) => {
if (Array.isArray(val)) {
let prevKey = currentKey;
currentKey = key;
this.addDocumentToArray(val, arr);
currentKey = prevKey;
} else {
arr.push({ documentID: val.documentID, displayName: `${currentKey || key}: ${val.displayName}` });
}
});
}