1

I want to flatten the items an array of objects and receive a new result array. How can I achieve it?

This approach did not work:

const group = [{
    idGroup: 1,
    member: [{
      name: "Tim"
    }, {
      name: "Sina"
    }]
  }],
}];

const result = [{
    idGroup: 1,
    name: "Tim"
  },
  {
    idGroup: 1,
    name: "Sina"
  },
]



const result = group.reduce((r, obj) => r.concat(obj.member), []);

console.log(result)

2

5 Answers 5

2

You could map nested objects.

const
    group = [{ idGroup:1, member: [{ name: "Tim" }, { name: "Sina" }] }];
    result = group.reduce(
        (r, { idGroup, member }) => [...r, ...member.map(({ name }) => ({ idGroup, name }))],
        []
    );

console.log(result);

Or use upcoming Array#flatMap.

const
    group = [{ idGroup:1, member: [{ name: "Tim" }, { name: "Sina" }] }];
    result = group.flatMap(({ idGroup, member }) =>
        member.map(({ name }) => ({ idGroup, name })));

console.log(result);

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

Comments

2

You can use flatMap() and use map() on member array of object.

const group = [
 {
  idGroup:1,
  member: [{name: "Tim"}, {name: "Sina"}],
 }
];

const res = group.flatMap(x => x.member.map(a => ({...a,idGroup:x.idGroup})));
console.log(res)

Comments

1

You'd need to use map too (to make the new items):

const group = [{idGroup:1,member:[{name: "Tim"},{name: "Sina"}]}];
const result = group.reduce((acc, { idGroup, member }) => acc.concat(member.map(({ ...props }) => ({ ...props, idGroup }), [])), []);
console.log(result);

Comments

1

You can use Array.prototype.reduce() and Array.prototype.forEach() like this:

const group = [{
  idGroup: 1,
  member: [{name: "Tim"}, {name: "Sina"}],
}, {
  idGroup: 2,
  member: [{name: "Jo"}, {name: "Eric"}]
}];

const result = group.reduce((acc, { idGroup, member }) => {
  member.forEach(({ name }) => acc.push({ idGroup, name }));
  return acc;
}, []);

console.log(result);

Comments

1

A good old loop can work too.

const group =
[{
    idGroup: 1,
    member: [{
      name: "Tim"
    }, {
      name: "Sina"
    }]
},
{
    idGroup: 2,
    member: [{
      name: "foo"
    }, {
      name: "bar"
    }, {
      name: "42"
    }]
}];

let result = [];

group.forEach((elem) => {
  elem.member.forEach((subElem) => {
    result.push({ idGroup: elem.idGroup, name: subElem.name });
  });
});

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.