[英]create an empty object based on pattern of another object
I have an object like this:我有一个像这样的 object:
const Media = {
references: { analyze: [432, 5], translate: ["string", false] },
extensions: { analyze: ["something"], translate: ["something here"] },
words: ["a word"],
brackets: [],
pronounce: [],
instructions: {
Expand_Explain: ['Before_First_Movie_Watch_Explain', 'Before_First_Movie_Watch_Explain2', 'Before_First_Movie_Watch_Explain3'],
Hot_Tutorial: ['1', 'some element', 2],
Next: [54, true, "string"],
}
}
And I want to create another object with only instructions
property with empty arrays inside:我想创建另一个 object ,其中只有
instructions
属性,内部为空 arrays :
So this is the desired result:所以这是期望的结果:
const NewEmptyMedia = {
instructions: {
Expand_Explain: [],
Hot_Tutorial: [],
Next: [],
}
}
Note: the pattern is the same for instructions
property always but the number of properties inside instructions
is variable.注意:
instructions
属性的模式始终相同,但instructions
中的属性数量是可变的。
I created a loop to do this but I need to check multiple if statements and it's really ugly...我创建了一个循环来执行此操作,但我需要检查多个 if 语句,这真的很难看......
You can use a reducer on Object.keys for Media.instructions.您可以在 Object.keys 上为 Media.instructions 使用减速器。
Something like this should suffice:像这样的东西就足够了:
Object.keys(Media.instructions).reduce((acc, key) => ({...acc, [key]: []}), {});
You can use a class, like this您可以使用 class,像这样
const Media = { references: { analyze: [432, 5], translate: ["string", false] }, extensions: { analyze: ["something"], translate: ["something here"] }, words: ["a word"], brackets: [], pronounce: [], instructions: { Expand_Explain: ['Before_First_Movie_Watch_Explain', 'Before_First_Movie_Watch_Explain2', 'Before_First_Movie_Watch_Explain3'], Hot_Tutorial: ['1', 'some element', 2], Next: [54, true, "string"], } } class EmptyMedia { constructor(template) { this.instructions = {}; for (const arr in template.instructions) { this.instructions[arr] = []; } } } console.log(new EmptyMedia(Media));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.