0

I have to convert,

string1 : "test1.$.test2",

into

test1:[{
    test2:"{value will be assign later in the code}"
}]

I have de structured the string into test1 and test2 using split function, which gives me

  • array name = test1
  • field name = test2

How do I construct the above format from string? or is there any function in lodash or any npm package I can use?

2
  • 2
    Where's your attempt? What have you tried? You should add that code to your question as a minimal reproducible example. Commented Aug 3, 2022 at 16:00
  • In order to get a good answer, you're going to need to provide more details on the format: Is it always just A.$.B, or can it get more complex? As far as I can tell, it's not any well-known format like JSONPath, so there's probably no library that automatically parses that string for you. Commented Aug 3, 2022 at 16:27

2 Answers 2

2

You can use { [myFieldVariable]: value } notation as follows:

myInput = "test1.$.test2"

fields = myInput.split('.$.'); // ['test1', 'test2']

myObject = {
    [fields[0]]: [ { [fields[1]]: "value assigned later" } ]
};

Now doing console.log(JSON.stringify(myObject, null, ' ')) shows that the object is in the structure you want.

{
   "test1": [
      {
         "test2": "value assigned later"
      }
   ]
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can match on test followed by a number to return an array of matches, and then use computed property names to build the data structure.

const str = 'test1.$.test2';
const [ first, second ] = str.match(/test\d/g);

const data = {
  [first]: [
    { [second]: '' }
  ]
};

console.log(data);

Additional documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.