如何在Javascript中复制Python的dict.items()? [英] How can I replicate Python's dict.items() in Javascript?
本文介绍了如何在Javascript中复制Python的dict.items()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Javascript中,我有一个JSON对象,我只想从中处理项目:
In Javascript I have a JSON object from which I want to process just the items:
var json = {
itema: {stuff: 'stuff'},
itemb: {stuff: 'stuff'},
itemc: {stuff: 'stuff'},
itemd: {stuff: 'stuff'}
}
在Python中,我可以做到
In Python I could do
print json.items()
[{stuff: 'stuff'},{stuff: 'stuff'},{stuff: 'stuff'},{stuff: 'stuff'}]
我可以这样做吗?
推荐答案
在不扩展Object.prototype的情况下,您无法像在python中那样进行此操作,而您不需要这样做,因为这是通往苦难的途径.
You cannot do this the same way as in python without extending Object.prototype, which you don't want to do, because it is the path to misery.
您可以轻松地创建一个辅助函数,该函数可以遍历对象并将值放入数组中,如下所示:
You could create a helper function easily that could loop over the object and put the value into an array however, like this:
function items(obj) {
var i, arr = [];
for(i in obj) {
arr.push(obj[i]);
}
return arr;
}
Ps:JSON是一种数据格式,您拥有的是对象文字.
Ps: JSON is a data format, what you have is an object literal.
这篇关于如何在Javascript中复制Python的dict.items()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文