0

This is the code:

var container_list = [
  {type: 'editor', id: 't1', placeholder: 'first section'},
  {type: 'onlytext', value: 'second section - only text'},
  {type: 'editor', id: 't2', placeholder: 'third section'},
  {type: 'editor', id: 't3', placeholder: 'fourth section', defvalue: JSON.stringify(formatted_content)}
]

const formatted_content = {"ops":[{"attributes":{"italic":true,"bold":true},"insert":"let's"},{"insert":" write "},{"attributes":{"underline":true},"insert":"something"},{"insert":" wonderful\n"}]}

This works flawlessly:

console.log(JSON.stringify(formatted_content)); 

But the result of:

console.log(container_list[3].defvalue);

is undefined .

How could i assign a JSON/variable to a property in an object? Thanks!

3
  • 1
    Look at your code. You define formatted_content after you define container_list, why would you expect that to work at all? Commented Mar 17, 2018 at 21:40
  • @Mike'Pomax'Kamermans Maybe because i started learning react and javascript together and one of the first example i saw was a component class in which a later declared variable was referenced, so i though javascript evaluates statement such a lazy way? Since my question i also figured out that before ES6 this kind of usage was working. I though stackoverflow is platform for asking questions. :) Commented Mar 19, 2018 at 21:43
  • Before ES6 this also didn't work. Variables are available only after declaration. Functions, on the other hand, are always hoisted, so (function() { var x = test(); function test() { return 'yes'; } console.log(x); })() will work just fine). If you copied this pattern from somewhere, please edit your post to point to where you found that pattern, because I would be incredibly surprised to learn that someone managed to write code where this did work. Commented Mar 19, 2018 at 23:09

1 Answer 1

3

Swap the sequence you declare these 2 constants. When you declare container_list, formatted_content is not yet defined

const formatted_content = {"ops":[{"attributes":{"italic":true,"bold":true},"insert":"let's"},{"insert":" write "},{"attributes":{"underline":true},"insert":"something"},{"insert":" wonderful\n"}]}

var container_list = [
  {type: 'editor', id: 't1', placeholder: 'first section'},
  {type: 'onlytext', value: 'second section - only text'},
  {type: 'editor', id: 't2', placeholder: 'third section'},
  {type: 'editor', id: 't3', placeholder: 'fourth section', defvalue: JSON.stringify(formatted_content)}
]

console.log(JSON.stringify(formatted_content));

console.log(container_list[3].defvalue);

Sign up to request clarification or add additional context in comments.

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.