node-object-mapper icon indicating copy to clipboard operation
node-object-mapper copied to clipboard

array mapping wraps destination in an unwanted array

Open lsimone opened this issue 7 years ago • 3 comments

As shown in my codesandbox, I tried to map as suggested in your readme, but I didn't find a way to remove the wrapping array from the destination object

const src = {
  foo: [{ bar: 4 }, { bar: 33 }]
};

const mapper = {
  "foo[].bar": "[]",
}

const res = map(src, mapper);
// res = [ [ 4, 33 ] ]
// i would expect [4, 33]

I would not expect to have a wrapping array in the result, and this behavior is a big restriction IMHO, because, for example, it seems impossible to use "append" + operator (useful to me) in order to build a collection from this object:

const src = {
  foo: [{ bar: 4 }, { bar: 33 }],
  bifoo: [{ bar: 77 }, { bar: 97 }]
};

const mapper = {
  "foo[].bar": "[]+",
  "bifoo[].bar": "[]+"
}

const res = map(src, mapper);
// res = [ [ 4, 33 ] ]
// i would expect [4, 33, 77, 97]

const mapper2 = {
  "foo[].bar": "num[]+",
  "bifoo[].bar": "num[]+"
}

const res = map(src, mapper2);
// res = { "num": [ [ 4, 33 ], [ 77, 97 ] ] }
// i would expect {"num": [4, 33, 77, 97] }

Why array items are not processed one at a time? Is it possible to easily achieve what I would like to?

lsimone avatar Mar 28 '18 16:03 lsimone

@lsimone Facing the same issue. Have you found any solution to this?

shwetajoshi601 avatar May 29 '18 09:05 shwetajoshi601

not yet @shwetajoshi601 . I'd like to solve it, maybe I'll fork because there are other use cases that I would like to handle...like computing destination value from several sources (i.e: dest.name = src.firstName || src.lastName )

lsimone avatar May 29 '18 19:05 lsimone

I see your point. The current functionality of + is specified as: stop what you are doing and add the data onto an array, for each item that has the +. I am not sure of the use case for this. @wankdanker may want to weigh in. I modified so that the + is specified as: add the results of this key to the existing array. If @wankdanker wants to leave as is, I'll back out this change.

switzer avatar Oct 11 '19 21:10 switzer