如何获取动态节点JSON值

时间:2018-01-04 14:46:58

标签: javascript json

   {       
        noteCount_xxx:
              {
              favorite:"favorite-border",
              id:"noteCount_xxx",
              note:"noteContent",
              title: "notetitle",
            }
    }
  • 此JSON数据在运行时创建,
  • noteCount_xxx 是动态的
  • 我想获得该父节点的价值
  • 输出

    {   最爱:"最喜欢的边界",   id:" noteCount_xxx",   注意:" noteContent",   标题:" notetitle" }

  

我无法从动态节点获取数据,获得该数据的最佳方法是什么   数据....?

2 个答案:

答案 0 :(得分:5)

您可以使用Object.keys查找nodeCount_xxx的值:

const yourJSON = {       
  noteCount_xxx:  {
    favorite:"favorite-border",
    id:"noteCount_xxx",
    note:"noteContent",
    title: "notetitle",
  }
}

const firstKey = Object.keys(yourJSON)[0]

console.log(yourJSON[firstKey])

如果您已经知道nodeCount_xxx的价值,只需访问您的对象:

yourJSON[noteCount]

答案 1 :(得分:0)

如果未正确转义值,则应动态创建对象:

var noteCount = "noteCount_" + 123

var parent = {
  favorite: "favorite-border",
  id: noteCount,
  note: "noteContent",
  title: "notetitle",
}

var person = { }
person[noteCount] = parent

console.log( parent )
console.log( person )
console.log( JSON.stringify( person ) )

如果JSON来自单独的进程,则可以在解析期间访问键值对:

var parent, currentNote = '{"noteCount_123":{"favorite":"favorite-border","id":"noteCount_123","note":"noteContent","title":"notetitle"}}'

var person = JSON.parse(currentNote, function(key, value) { 
  return key ? parent = value : value })

console.log( parent )
console.log( person )