0

I have a large JS object which I feed to a factory. The original object contains strings in an array which are a parameter for the factory.

I would like to shorten the code to as short as possible and hopefully be functional.

What I have so far:

const myConfigObject = {
  label: 'something',
  children: [
    {
      id: 'one',
      style: 'some style',
      children: ['key1', 'key2']
    },
    {
      id: 'two',
      style: 'some other style',
      children: ['key3', 'key4']
    },
  ]
}

function DummyFactory (key) {
  return {
    id: key,
    data: 'generated stuff'
  };
}

// How to optimize this call?
myConfigObject.children.forEach(child => {
  child.children = child.children.map(subChild => DummyFactory(subChild))
});

console.log(myConfigObject);

4
  • What's your problem here? Commented May 3, 2018 at 17:37
  • 1
    What do you mean by "optimize"? If you must to visit each string, you can't reduce iterations number.. May be use webworkers to parallelize the work? Commented May 3, 2018 at 17:38
  • IMHO this is already pretty well optimized; if you're still looking for pointers, this should go on codereview.stackexchange.com Commented May 3, 2018 at 17:38
  • I was hoping to reduce it to a one liner Commented May 3, 2018 at 17:41

3 Answers 3

2

There's not much to do here, but I would go for

function DummyFactory(key) {
  return {
    id: key,
    data: 'generated stuff'
  };
}
const myConfigObject = {
  label: 'something',
  children: [
    {
      id: 'one',
      style: 'some style',
      children: ['key1', 'key2'].map(DummyFactory)
    },
    {
      id: 'two',
      style: 'some other style',
      children: ['key3', 'key4'].map(DummyFactory)
    },
  ]
};
Sign up to request clarification or add additional context in comments.

Comments

1

Trying to shortening:

myConfigObject.children.forEach(
 child => child.children = child.children.map(DummyFactory));

Comments

0

To achieve expected use below option of even avoiding DummyFactory

myConfigObject.children.forEach(child => {
  child.children = child.children.map(subChild=> {
  return {
    "id":subChild,
    "data": 'generated stuff'
    }   
  })
});

code sample - https://codepen.io/nagasai/pen/VxWJYd?editors=1010

const myConfigObject = {
  label: 'something',
  children: [
    {
      id: 'one',
      style: 'some style',
      children: ['key1', 'key2']
    },
    {
      id: 'two',
      style: 'some other style',
      children: ['key3', 'key4']
    },
  ]
}


myConfigObject.children.forEach(child => {
  child.children = child.children.map(subChild=> {
  return {
    "id":subChild,
    "data": 'generated stuff'
    }   
  })
});

console.log(myConfigObject);

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.