问题
I'm trying to record an objects movements with an attached attribute called data-settings
so far I have managed to set up some sort of JSON/Array but I want one of the objects to hold multiple arrays of hashes like so.
{ nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 }], [{ posX: newPX, posY: newPY, time: 5 }] }
However I'm struggling to add another array to the moves
so I only have this:
{ nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 }] }
How do I push an array with hashes to moves
?
Thanks
回答1:
el = { nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 }] }
el.moves.push({ posX: newPX, posY: newPY, time: 5 })
Gives:
{ nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 },{ posX: newPX, posY: newPY, time: 5 }] }
Your original syntax isn't valid as you have two arrays containing a single object each attached to the "moves" key. It's not valid JSON.
See : http://www.json.org/
回答2:
No extra square brackets required. So:
moves: [
{ posX: newPX, posY: newPY, time: 0 },
{ posX: newPX, posY: newPY, time: 5 }
]
来源:https://stackoverflow.com/questions/7492472/how-do-i-add-a-array-to-a-json-object