将JSON对象作为字符串分配给Javascript中对象中的属性

时间:2018-03-17 19:14:16

标签: javascript javascript-objects

这是代码:

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"}]}

这完美无缺:

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

但结果是:

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

未定义

我如何将JSON /变量分配给对象中的属性? 谢谢!

1 个答案:

答案 0 :(得分:3)

交换声明这两个常量的序列。当您声明container_list时,formatted_content尚未定义

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);

相关问题