How do I add a Array to a JSON object

2019-09-11 20:14发布

问题:

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


标签: arrays json push