开发者

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

开发者 https://www.devze.com 2023-02-17 15:16 出处:网络
In Javascript I have a JSON object from which I want to process just the items: var json = { itema: {stuff: \'stuff\'},

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: {stuf开发者_开发问答f: 'stuff'}
}

In Python I could do

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

Can I do this is js?


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.


Thanks to recent updates to JavaScript - we can solve this now:

function items(iterable) {
    return {
        [Symbol.iterator]: function* () {
            for (key in iterable) {
                yield [key, iterable[key]];
            }
        }
    };
}

for (const [key, val] of items({"a": 3, "b": 4, "c": 5})) {
    console.log(key, val);
}
// a 3
// b 4
// c 5

for (const [key, val] of items(["a", "b", "c"])) {
    console.log(key, val);
}
// 0 a
// 1 b
// 2 c


ubershmekel's answer makes use of lazy evaluation, compared to my answer below which uses eager evaluation. Lazy evaluation has many benefits which make it much more appropriate for performance reasons in some cases, but the transparency of eager evaluation can be a development speed boon that may make it preferable in other cases.

const keys = Object.keys;

const values = object =>
  keys(object).map(key => object[key]);

const items = object =>
  keys(object).map(key => [key, object[key]])


obj = {a: 10, b: 20, c: 30};

keys(obj)   // ["a", "b", "c"]
values(obj) // [10, 20, 30]
items(obj)  // [["a", 10], ["b", 20], ["c", 30]]

items(obj).forEach(([k, v]) => console.log(k, v))
// a 10
// b 20
// c 30


Not sure what you want to do but I guess Json.stringify will do something like that. See http://www.json.org/js.html

0

精彩评论

暂无评论...
验证码 换一张
取 消