3

I try to merge two arrays of objects and at the same time add their name as a property to the objects:

const firstGroup = [
    {
        firstname: 'Nick',
        id: 1
    },
    {
        firstname: 'Joe',
        id: 2
    },
]

const secondGroup = [
    {
        firstname: 'Tom',
        id: 1
    },
]

The desired output:

allGroups = [
    {
        groupname: 'firstGroup',
        firstname: 'Nick',
        id: 1
    },
    {
        groupname: 'firstGroup',
        firstname: 'Joe',
        id: 2
    },
    {
        groupname: 'secondGroup',
        firstname: 'Tom',
        id: 1
    }
]

Here is what I tried:

Object
    .entries({ firstGroup, secondGroup })
    .reduce((acc, [name, [firstname, id]]) => ([{
        ...acc,
        groupname: name,
        firstname,
        id
    }]), [])

But it doesn't work and I can't figure out how I can do it.

Thanks for your help !

3
  • You'll have to pass the group names in explicitly, as the names of the source variables are not available in the function. Commented Dec 5, 2019 at 16:42
  • 1
    @Pointy - The OP had a clever solution to that: shorthand property notation creating an object. :-) Commented Dec 5, 2019 at 16:46
  • @T.J.Crowder ah ok I see that now, well that's well and good but it still essentially hard-codes the "group" names, which is fine by me of course. Commented Dec 5, 2019 at 16:54

4 Answers 4

4

Your code was close, but you're creating a new array on each iteration rather than modifying the "accumulator" array reduce passes around, and only taking the properties from the first entry in the source array, not all of them.

reduce just adds complexity here IMHO, I'd use a for-of loop over the entries of the object you created. Within the loop body, map the entries to new entries with the group name, then push them all on allGroups. Like this:

const allGroups = [];
for (const [groupname, entries] of Object.entries({firstGroup, secondGroup})) {
    allGroups.push(...entries.map(entry => ({groupname, ...entry})));
}

Live Example:

const firstGroup = [
    {
        firstname: 'Nick',
        id: 1
    },
    {
        firstname: 'Joe',
        id: 2
    },
];

const secondGroup = [
    {
        firstname: 'Tom',
        id: 1
    },
];

const allGroups = [];
for (const [groupname, entries] of Object.entries({firstGroup, secondGroup})) {
    allGroups.push(...entries.map(entry => ({groupname, ...entry})));
}
console.log(allGroups);

But here's a working version of your reduce approach:

const firstGroup = [
    {
        firstname: 'Nick',
        id: 1
    },
    {
        firstname: 'Joe',
        id: 2
    },
];

const secondGroup = [
    {
        firstname: 'Tom',
        id: 1
    },
];

const allGroups = Object.entries({ firstGroup, secondGroup })
    .reduce((acc, [groupname, entries]) => {
        acc.push(...entries.map(entry => ({groupname, ...entry})));
        return acc;
    }, []);
console.log(allGroups);


In a comment you've asked:

...what if I want in the final object just a selection of the initial properties eg. groupname, firstname but not id ?

You'd change the places above where I have entry => to ({firstname}) => to destructure the listed property(ies) from the object, and change where I have ...entry to firstname to fill in just that/those properties on the new object. So for instance:

allGroups.push(...entries.map(({firstname}) => ({groupname, firstname})));

Live example - for-of:

const firstGroup = [
    {
        firstname: 'Nick',
        id: 1
    },
    {
        firstname: 'Joe',
        id: 2
    },
];

const secondGroup = [
    {
        firstname: 'Tom',
        id: 1
    },
];

const allGroups = [];
for (const [groupname, entries] of Object.entries({firstGroup, secondGroup})) {
    allGroups.push(...entries.map(({firstname}) => ({groupname, firstname})));
}
console.log(allGroups);

Live example - reduce:

const firstGroup = [
    {
        firstname: 'Nick',
        id: 1
    },
    {
        firstname: 'Joe',
        id: 2
    },
];

const secondGroup = [
    {
        firstname: 'Tom',
        id: 1
    },
];

const allGroups = Object.entries({ firstGroup, secondGroup })
    .reduce((acc, [groupname, entries]) => {
        acc.push(...entries.map(({firstname}) => ({groupname, firstname})));
        return acc;
    }, []);
console.log(allGroups);

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

4 Comments

The for ... of loop is fine. But what if I want in the final object just a selection of the initial properties eg. groupname, firstname but not id ?
@Tom - I've updated the answer to show how to do that.
I missed the brackets when destructuring firstname. Sorry I can't vote twice... Thanks a lot
@Tom - Happy to help! I really go back and forth on the question of whether to leave out the optional () around an arrow function's parameter list if there's just one non-destructured parameter. If I'd included them here, you wouldn't have run into trouble. :-)
1

Below snippet of code can be used to achieve the result.

Object.entries({ firstGroup, secondGroup }).reduce((acc, [groupname, groupItems]) => {

for (item of groupItems){

    acc.push({
    ...item,
    groupname
    });
}

return acc; 

}, [])

Comments

1

If you have access to it, you can use flatMap or flat to avoid using reduce entirely.

Passing an array to reduce and pushing an item onto the accumulator per element is an antipattern because map does this specific operation (applying a callback to every item in an array) with cleaner syntax and semantics. The only reason reduce was chosen is because a flattening operation is needed, but flatMap expresses this intent more clearly.

const firstGroup = [{firstname: 'Nick', id: 1}, {firstname: 'Joe', id: 2}]; 
const secondGroup = [{firstname: 'Tom', id: 1}];

const result = Object.entries({firstGroup, secondGroup})
  .flatMap(([groupname, arr]) => arr.map(({id, firstname}) => ({
    groupname, firstname, id
  })))
;
console.log(result)

Using flat:

const firstGroup = [{firstname: 'Nick', id: 1}, {firstname: 'Joe', id: 2}]; 
const secondGroup = [{firstname: 'Tom', id: 1}];

const result = Object.entries({firstGroup, secondGroup})
  .map(([groupname, arr]) => arr.map(({id, firstname}) => ({
    groupname, firstname, id
  })))
  .flat()
;
console.log(result)

If you don't have access to either, there's spread/concat:

const firstGroup = [{firstname: 'Nick', id: 1}, {firstname: 'Joe', id: 2}]; 
const secondGroup = [{firstname: 'Tom', id: 1}];

const result = [].concat(...Object.entries({firstGroup, secondGroup})
  .map(([groupname, arr]) => arr.map(({id, firstname}) => ({
    groupname, firstname, id
  }))))
;
console.log(result)

Comments

-1

No need to over complicate things, this will work just fine:

const firstGroup = [
    {
        firstname: 'Nick',
        id: 1
    },
    {
        firstname: 'Joe',
        id: 2
    },
]

const secondGroup = [
    {
        firstname: 'Tom',
        id: 1
    },
]

firstGroup.map(x => x.groupname = 'firstGroup');
secondGroup.map(x => x.groupname = 'secondGroup');

const allGroups = [].concat(firstGroup, secondGroup);
console.log(allGroups);

6 Comments

You definitely do not, that example runs just fine.
If you're not using the return value of map (the array it creates), map isn't the right tool. For the above, you'd want forEach, for-of, or a simple for loop. Other than that, yeah, if it's okay to modify the existing objects, this is nice and simple and gets the job done.
I disagree, the map function is perfect for this as I'm altering the structure of the object in those arrays.
@nerdybeast you can do that in a .forEach() loop too. There's no need for .map().
@nerdybeast It works, but since you're using map, it will return a new array. Since you're not making use of that array, you might as well use forEach instead - it'll have the same output
|

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.