反向 json javascript
是否有一种廉价的方法来反转:
{
"10": "..."
"11": "...",
"12": "...",
"13": "...",
"14": "...",
}
以便我得到:
{
"14": "...",
"13": "...",
"12": "..."
"11": "...",
"10": "...",
}
reverse() 似乎不适用于 json 对象。我能想到的唯一方法是循环所有元素并创建一个数组。感觉应该有更好的办法。
编辑:感谢您的所有帮助更新:
如果每个键都有按时间顺序排列的数据呢?当我在对象上使用 $.each 时,它从上到下遍历对象,我没有意识到这是不可靠的。
这就是我想要做的:
$.each(object, function (key, value) {
function foo (key, value);
});
除了最后 3 对之外,我不想对所有其他都运行 foo,也就是说我只想使用最后 3 对。我想如果我能逆转它们,我就可以跑前三个然后停下来。
有什么办法可以只完成最后3个吗?如果最后 3 个排序不可靠,是否有更安全的方法来获取最后 3 个。最后 3 个将具有最大的数字键。
谢谢。
编辑2: 我基本上最终决定在服务器端进行操作。我正在重新组织我的数据库,以便相关子文档现在已包含可以使用 mongodb 查询的文档。谢谢。
Is there an inexpensive way to reverse:
{
"10": "..."
"11": "...",
"12": "...",
"13": "...",
"14": "...",
}
so that I get:
{
"14": "...",
"13": "...",
"12": "..."
"11": "...",
"10": "...",
}
reverse() doesn't seem to work on json objects. The only way I can think of is to loop through all the elements and create an array. feels like there should be a better way.
Edit: thanks for all the help UPDATE:
What about let's say if each key has chronological data. When I use $.each on the object, it runs through the objects from top to bottom, I didn't realize that was unreliable.
Here's what I'm trying to do:
$.each(object, function (key, value) {
function foo (key, value);
});
I want to not run foo on all but the last 3 pairs, that is I only want to use the last 3 pairs. I figured if I can reverse them I can just run the first three and stop.
Is there any way I can just do the last 3? If the last 3 ordering is unreliable, is there a safer way to grab the last 3. The last 3 will have the largest numerical keys.
Thanks.
Edit 2:
I'm basically deciding finally to do the manipulations on the server side. I'm reorganizing my database so that the relevant subdocuments are now full on documents that could be queried with mongodb. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
JavaScript 关联数组是无序的。您不能依赖于任何特定顺序的属性。
来自 Mozilla 开发者网络:
Javascript associative arrays are unordered. You cannot depend on the properties being in any particular order.
From Mozilla Developer Network:
在 json 对象数组上使用它
希望这有帮助
Use this on json objects arrays
Hope this helps
这可能会有所帮助。将 json 对象中的所有键获取到一个数组中,您可以对其进行排序。
然后你可以使用reverse()和slice()来迭代你需要的键。
This might help. Get all the keys from the json objects into an array, which you can sort.
then you can use reverse() and slice() to just iterate over the keys you need.
按照相反的顺序遵循 json,
Follow the json in reverse order,