create an empty object based on pattern of another object

I have an object like this:

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:

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.

I created a loop to do this but I need to check multiple if statements and it’s really ugly…

3 thoughts on “create an empty object based on pattern of another object”

  1. You can use a reducer on Object.keys for Media.instructions.

    Something like this should suffice:

    Object.keys(Media.instructions).reduce((acc, key) => ({...acc, [key]: []}), {});
    
    Reply
  2. You can use a class, like this

    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));
    Reply

Leave a Comment