Tom
Tom

Reputation: 165

Merge two arrays of objects and add array name as a property

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 !

Upvotes: 3

Views: 242

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1075337

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

Upvotes: 4

ggorlen
ggorlen

Reputation: 57214

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)

Upvotes: 1

N.K.
N.K.

Reputation: 464

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; 

}, [])

Upvotes: 1

nerdy beast
nerdy beast

Reputation: 789

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

Upvotes: -1

Related Questions