How can I replicate Python's dict.items() in Javascript?

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 is a data format, what you have is an object literal.


In python dict.items returns a list of tuples containing both the keys and the values of the dict. Javascript doesn't have tuples, so it would have to be a nested array.

If you'll excuse me a little python code to show the difference.

>>> {1:2, 2:3}.items()
[(1, 2), (2, 3)]
>>> {1:2, 2:3}.values()
[2, 3]

I see the accepted answer returns an array of the objects values, which is the equivalent of the python function dict.values. What is asked for is dict.items. To do this just loop and build up a nested array of 2 element arrays.

function items(obj){

    var ret = [];
    for(v in obj){
        ret.push(Object.freeze([v, obj[v]]));
    }
    return Object.freeze(ret);
}

I put the Object.freeze in to be pedantic and enforce that the returned value shouldn't be altered, to emulate the immutability of python tuples. Obviously it still works if you take it out.

It should be noted that doing this somewhat defeats the purpose of items in that it is used when iterating over the object in a linear rather than associative fashion and it avoids calculating the hash value to look up each element in the associative array. For small objects who cares but for large ones it might slow you down and there might be a more idiomatic way to do what you want in javascript.

Another newer way to do it is to use Object.entries() which will do exactly what you want.

Object.entries({1:1, 2:2, 3:3})
      .forEach(function(v){
          console.log(v)
      });

The support is limited to those browser versions mentioned in the documentation.