如何将数组添加到JSON对象

如何将数组添加到JSON对象

本文介绍了如何将数组添加到JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我正在尝试使用名为data-settings的附加属性记录对象的运动,到目前为止,我已经设法设置了某种JSON/Array,但我希望其中一个对象能够像这样保存多个哈希数组.

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

但是我正在努力向moves添加另一个数组,所以我只有这个:

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

如何将带有散列的数组推入moves?

How do I push an array with hashes to moves?

谢谢

推荐答案

el = { nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 }] }
el.moves.push({ posX: newPX, posY: newPY, time: 5 })

赠予:

{ nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 },{ posX: newPX, posY: newPY, time: 5 }] }

您的原始语法无效,因为您有两个数组,每个数组都包含一个对象,每个对象都附加到"moves"键上.这不是有效的JSON.

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.

请参阅: http://www.json.org/

这篇关于如何将数组添加到JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:06