Monday, 27 August 2018

How to "expand" sub array in array of objects

This is my array of objects

[{
    "key1": "value1",
    "key2": "value2",
    "key3": ["value3", "value4"]
}]

The result should be like this

[{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}, {
    "key1": "value1",
    "key2": "value2",
    "key3": "value4"
}]

So I want to get rid of the sub array in property key3 and get the new equivalent structure, copying all the other properties.

For reasons I cannot change I am supposed to use lodash, but only in version 2.4.2

EDIT: To be more elaborate: I am using a JSON based form engine which allows to use existing functions (like lodash functions) but doesn't allow to define new functions. I also cannot use control structures like for loops. Essentially I can only use chained basic function calls including lodash.

I tried to use map, but map cannot extend an array, it can only convert one array element into something different

Is there any lodash magic I can use here?

EDIT2: Here is an example about what I mean when I say "I cannot introduce new functions". It will check if an array of objects is unique regarding a certain subset of properties

model = [{
    "key1": "value1",
    "key2": "value2",
    "key3": "valuex"
},{
    "key1": "value1",
    "key2": "value2",
    "key3": "valuey"
}]

// will give false because the two objects are not unique regarding the combination of "key1" and "key2"
_.uniq(model.map(_.partialRight(_.pick, ["key1", "key2"])).map(JSON.stringify)).length === model.length



from How to "expand" sub array in array of objects

No comments:

Post a Comment