How can I copy Python dict.items () in Javascript?

In Javascript, I have a JSON object from which I want to process only elements:

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 it? js?

+8
source share
5 answers

You cannot do it the same way as in python without extending Object.prototype, which you do not want to do, because this is the path to suffering.

You can easily create a helper function that could loop around the object and put the value in an array, 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.

+3
source

python dict.items , , dict. Javascript , .

python, .

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

, , python dict.values. dict.items. 2 .

function items(obj){

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

Object.freeze , , python. , , .

, items , , , - . , , , , , javascript.

- Object.entries(), , .

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

, .

+1

JavaScript - :

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
+1

ubershmekel , , . , , , .

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
0

, , , Json.stringify - . . http://www.json.org/js.html

-3

All Articles