2

I converted this object into JSON string. values of subject1, subject2, subject 3 are coming from input fields in angular frontend

subject = {
    "subject1": "A",
    "subject2": "B",
    "subject3": "C"
}

and now I have a JSON string like this,

const subjects = {"subject1": "A", "subject2": "B","subject3":"c"}

Like this, I saved this as a JSON string in DB. In another place, I wanted to access this string as an object as previously I made. to output these subjects separately as same as It gets as an object.

example:- First input box - subject1 value as A , Second input box - subject2 value as B

How can I put them back again like separate values into separate variables or any other way to separate them and put back into the text fields?

I just tried to get that JSON string and tried to access subject1 like subject1 = subjects.subject1 like that I can put subject1 in relevant text field. But that doesn't work. I checked previous questions like this. But they didn't answer my question. How can I solve this?

0

2 Answers 2

4

You can do it with JSON.parse.

  const obj = JSON.parse(subjects);
  console.log(obj.subject1);  // "A"
Sign up to request clarification or add additional context in comments.

Comments

2

You can use destructuring assignment:

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

const subject = {
    "subject1": "A",
    "subject2": "B",
    "subject3": "C"
}

const {subject1,subject2,subject3} = subject;

console.log(subject1);
console.log(subject2);
console.log(subject3);

You can find more about destructuring assignment here

1 Comment

That's cool. Thank you. I was looking for this for a long time.

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.