Complex objects in javascript

I was messing around with a library called bcoinfor node. Execution of the following code:

  chain.on('block', function(block) {
    console.log('Connected block to blockchain:');
    block.txs.forEach(function(t) {
      t.inputs.forEach(function(i) {
        console.log(typeof i, i);
        console.log(JSON.stringify(i));
      });
    });
  });

This is the answer I get:

Connected block to blockchain:
object { type: 'coinbase',
  subtype: null,
  address: null,
  script: <Script: 486604799 676>,
  witness: <Witness: >,
  redeem: null,
  sequence: 4294967295,
  prevout: <Outpoint: 0000000000000000000000000000000000000000000000000000000000000000/4294967295>,
  coin: null }
{"prevout":{"hash":"0000000000000000000000000000000000000000000000000000000000000000","index":4294967295},"script":"04ffff001d02a402","witness":"00","sequence":4294967295,"address":null}

Note that although an attribute type, for example, is displayed when printing i, this attribute does not exist when we are JSON.stringifyan object. If I tried console.log(i.type), I would get undefined.

How is this possible? And what is a good way to debug what happens to an object?

+4
source share
1 answer

JSON.stringify will include only the listed properties that are not functions.

So, if you define a property and set it to non-enumerable, it will not be part of the JSON string.

var obj = {
  a: 'test'
};

// Non-enumerable property
Object.defineProperty(obj, 'type', {
  enumerable: false,
  value: 'Test'
});

// Get property
Object.defineProperty(obj, 'type2', {
  get: function(){
    return 'Test 2'
  }
});


console.log(JSON.stringify(obj), obj);
console.log(obj.type, obj.type2)
Run codeHide result

enter image description here

+1
source

Source: https://habr.com/ru/post/1688051/


All Articles