0

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...

2
  • Why not just hand code it if it will have not values and only structure? Why do you see a need to refer to a different object when "the pattern is the same for instructions property always"? Commented Feb 18, 2021 at 17:42
  • @ Randy Casburn Sometimes you just need it... Commented Feb 18, 2021 at 17:49

2 Answers 2

2

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]: []}), {});
Sign up to request clarification or add additional context in comments.

2 Comments

The result of this is what NewEmptyMedia.instructions should be, I think
function getNewMedia() { return {instructions: Object.keys(Media.instructions).reduce((acc, key) => ({...acc, [key]: []}), {})}; }
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.