javascript 中的关联数组到 JSON
我使用数组作为对象的关联数组,其中键是数据库中对象的 ID 号。自然安静 - ID 是很大的数字 - 因此这意味着长度为 10^4 的数组通常只有 20 个元素作为有效的真实对象。
我想将这些数据发送回服务器,但是无论我必须使用什么插件将 js 对象转换为 JSON,我都尝试了它们 &它们都会生成长度为 10^4 的 JSON 字符串。这么多数据发不回来。
我需要一种将关联数组转换为 JSON 并丢弃未定义条目的方法。
有什么建议吗?
编辑: 我的数组的示例: var myAssociativeArray = [未定义,未定义,未定义....,某个对象,其他一些对象...,未定义,...又一个....]
I am using array as an associative array of objects in which keys are ID number of objects in database. Quiet naturally- IDs are large numbers - so that means it is common to have array of length 10^4 with only 20 elements as valid real objects.
I want to send this data back to server but whatever plugins I had to convert js objects to JSON- I tried them all & they all produce a JSON string of length 10^4. So much data can't be sent back.
I need a way of converting associative array to JSON discarding undefined entries.
Any suggestions ?
EDIT:
Example of what my array looks like :
var myAssociativeArray = [undefined, undefined,undefined...., someobject, some other object ...,undefined, ... yet another....]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来你有一个常规数组,但你使用它时就好像它是稀疏的(它可能是也可能不是内部的)。以下是如何使用替换函数来转换为对象:
It sounds like you have a regular array, but you're using it as if it were sparse (which it may or may not be internally). Here's how to use a replacer function that will convert to an object:
阅读你的问题,看起来正在使用数组。这是一种仅获取数组中已定义条目的解决方案(不保证顺序)。
请注意,由于它是一个稀疏数组,例如最多可以达到 10000,因此最好只枚举属性,而不是实际从 0 到 9999 循环,因为它们中的大多数无论如何都是未定义的。所以这对于性能来说更好。
然后将
defineEntries
发送到服务器。Reading your question, it looks are using an array. Here's one solution to get only the defined entries of the array (order not guaranteed).
Note that since it is a sparse array and can go upto 10000 for instance, it's better to only enumerate the properties and not actually loop from 0 to 9999, as most of them will be undefined anyways. So this is better for performance.
Then send
definedEntries
to the server.