1

i have an array like this :

const toto = [{ id: 1, arrays: [{ id: 1, name: 'tatat' }, { id: 2, name: 'tutu' }] };

And i'd like to get :

[{ id: 1, arrays: [{ id: 1, name: 'tatat' }] }, { id: 1, arrays: [{ id: 2, name: 'tutu' }] }];

This is what i did :

const aEvt = [];
this.organization.events.forEach(x => {
  const e = Object.assign({}, x);
  if (x.eventToOrganizators.length > 1) {
    x.eventToOrganizators.forEach(y => {
      console.log('y', y);
      e.eventToOrganizators = [y];
      console.log('e', e.eventToOrganizators[0]); // OK get the good value
      aEvt.push(e);
    });
  } else {
    aEvt.push(e);
  }
});
console.log(aEvt); // NOT OK, e.eventToOrganizators[0] has all the time the same value

2 Answers 2

1

You could take Array#flatMap for the outer and Array#map for the nested array.

const 
    data = [{ id: 1, arrays: [{ id: 1, name: 'tatat' }, { id: 2, name: 'tutu' }] }],
    result = data.flatMap(({ arrays, ...o }) =>
        arrays.map(item => ({ ...o, arrays: [item] }))
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm, but didn't understand why my ugly solutions didn't works.
1

You can do something like this:

const toto = [{
  id: 1,
  arrays: [{
    id: 1,
    name: 'tatat'
  }, {
    id: 2,
    name: 'tutu'
  }]
}];

const result = toto.reduce((a, c) => {
  const elements = c.arrays.map(e => ({
    ...c,
    arrays: [e]
  }));
  return [...a, ...elements];
}, []);

console.log(result);

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.