Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

In Python I could do

print json.items()
[{stuff: 'stuff'},{stuff: 'stuff'},{stuff: 'stuff'},{stuff: 'stuff'}]

Can I do this is js?

like image 418
Col Wilson Avatar asked Mar 17 '11 11:03

Col Wilson


People also ask

What does DICT items () method return?

Python Dictionary items() Method The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.

What does DICT items () do in Python?

In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Parameters: This method takes no parameters. Returns: A view object that displays a list of a given dictionary's (key, value) tuple pair.

What is equivalent of dictionary in JavaScript?

Actually there is no 'dictionary' type in JavaScript but we can create key-value pairs by using JavaScript Objects. Create a new JavaScript Object which will act as dictionary. Syntax: Key can be a string , integer. If you just write key1 or any number, it will treat as a string.

What is a Python dictionary called in JavaScript?

In statically typed programming languages a Dictionary (Key/Value pair collection) object can be very useful at times. While JavaScript doesn't natively include a type called “Dictionary”, it does contain a very flexible type called “Object”.


2 Answers

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.

like image 87
Martin Jespersen Avatar answered Oct 19 '22 13:10

Martin Jespersen


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.

like image 33
Paul Rooney Avatar answered Oct 19 '22 11:10

Paul Rooney