简体   繁体   中英

Transform array of objects into array of objects with an extra property with map, filter, reduce

I have the following array of objects:

[
{id: 1, updatedVersion: 7},
{id: 2, updatedVersion: 0},
{id: 7, updatedVersion: 9},
{id: 10, updatedVersion: 11},
{id: 9, updatedVersion: 0},
{id: 11, updatedVersion: 0},
]

Those with updatedVersion equal to zero are the latest versions.

From that array I was able to filter the ones that are the latest version and have at least one previous Version, which are objects with id 9, and 11. (Object with id === 2 is not included since it's the latest version but has no previous versions).

What I need now is to create an extra property in those two objects with id 9 and 11 (again: the objects that are latest version and have at least one previous version), called versionHistory, which would be an ordered array of previous versions of that object, from most recent to oldest.

So it would look something like that:

[
    {   id: 9, 
        updatedVersion: 0, 
        versionHistory: [
            {id: 7, updatedVersion: 9},
            {id: 1, updatedVersion 7}
        ]
    },
    {
        id: 11,
        updatedVersion: 0,
        versionHistory: [
            {id: 10, updatedVersion: 11}
        ] 
    }
]

I came up with an ugly solution that involves nested for loops but I'm looking for something more elegant that uses map, filter and reduce. I would appreciate any hints on how to approach this.

This isn't terribly efficient but hopefully meets the "elegant" requirement ;)

 data = [ {id: 1, updatedVersion: 7}, {id: 2, updatedVersion: 0}, {id: 7, updatedVersion: 9}, {id: 10, updatedVersion: 11}, {id: 9, updatedVersion: 0}, {id: 11, updatedVersion: 0}, ] let prev = node => data.find(n => n.updatedVersion === node.id); let path = node => node ? [node, ...path(prev(node))] : []; let result = data.filter(n => n.updatedVersion === 0).map(node => ({ versionHistory: path(node).slice(1), ...node, })); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM