Skip to content
Advertisement

Add complex array of objects into another object

I have an source object obj that looks like this and an array input

JavaScript

I need to push objects that are formed after spiltting input by . After splitting, using left side of the string i need to form an object like this

{ type: "type1", value: whatever the left hand value}

Same for right side value

{ type: "type2", value: whatever the right hand value}

And these objects should be pushed to innermost and in the source object.

Expected output

JavaScript

Code that I tried

JavaScript

Advertisement

Answer

Assuming that the input array would include an escape character and could be like so: ["test1\name1", "test2\name2"], presented below is one possible way to achieve the desired objective.

Code Snippet

JavaScript
JavaScript

Explanation

Inline comments added to the snippet above.

EDIT

the left and right side value after splitting can be present in different items in the array too. How can I have only unique type1 , type2 objects inside final array

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement