wankdanker / node-object-mapper

Copy properties from one object to another.
MIT License
277 stars 73 forks source link

Including parent items in arrays #50

Open RJFoster opened 6 years ago

RJFoster commented 6 years ago

Is it possible to include parent items when mapping arrays For example, if I have:

{
    "a": "AA",
    "b": "BB",
    "array": [
        { "x": "one" },
        { "x": "two" }
    ]
}

and I want to convert it to:

{
    "results": [
        {
            "aye": "AA",
            "bee": "BB",
            "ex": "one"
        },
        {
            "aye": "AA",
            "bee": "BB",
            "ex": "two"
        }
    ]
}

I've tried to use a map something like:

map = {
    "a": "results[].aye",
    "b": "results[].bee",
    "array[].x": "results[].ex"
}

But I get:

{
    results: [ 
        { aye: 'AA', bee: 'BB', ex: 'one' },
        { ex: 'two' } 
    ]
}

Obviously the second array element isn't what I want. Presumably I could use a transform, but with more complex examples I would essentially just be mapping using JavaScript

liangde-chen commented 6 years ago

I have same requirement

iandecroix commented 5 years ago

Have you guys figured out how to work with this?

switzer commented 5 years ago

This is a good point. I have a version working, but there is a trick. The map has to have the instruction to create all array nodes first, then to populate, as follows:

map = {
    "array[].x": "results[].ex",
    "a": "results[].aye",
    "b": "results[].bee"
}

This would be a new feature, and it breaks a couple of existing tests. @wankdanker what are your thoughts about this?

HemalathaBR commented 4 years ago

Any updates on this? I am having similar requirement.

emmartu commented 3 years ago

I've fixed it on my own. I've also launched the complete test suite successfully

kiennt2 commented 1 year ago

Hi @emmartu , i have same requirement, could you share your knowledge, Thank you.

I've fixed it on my own. I've also launched the complete test suite successfully