I'm fiddling around with a library called bcoin for node. Running 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 response I'm getting:
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}
Notice that even though the attribute type for example, is shown when we print i, that attribute does not exist when we JSON.stringify the object. If I tried to console.log(i.type) I'd get undefined.
How is that possible? And what is a good way of debugging what's going on with an object?
JSON.stringify will only includes enumerable properties that are not functions.
So if you define a property and set as non-enumerable, it will not be a part of 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)
Related
I was playing with below javascript code. Understanding of Object.defineProperty() and I am facing a strange issue with it. When I try to execute below code in the browser or in the VS code the output is not as expected whereas if I try to debug the code the output is correct
When I debug the code and evaluate the profile I can see the name & age property in the object
But at the time of output, it only shows the name property
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true
})
console.log(profile)
console.log(profile.age)
Now expected output here should be
{name: "Barry Allen", age: 23}
23
but I get the output as.
Note that I am able to access the age property defined afterwards.
I am not sure why the console.log() is behaving this way.
{name: "Barry Allen"}
23
You should set enumerable to true. In Object.defineProperty its false by default. According to MDN.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
Non-enumerable means that property will not be shown in Object.keys() or for..in loop neither in console
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
All the properties and methods on prototype object of built-in classes are non-enumerable. Thats is the reason you can call them from instance but they don't appear while iterating.
To get all properties(including non-enumerable)Object.getOwnPropertyNames()
.
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: false
})
for(let key in profile) console.log(key) //only name will be displayed.
console.log(Object.getOwnPropertyNames(profile)) //You will se age too
By default, properties you define with defineProperty are not enumerable - this means that they will not show up when you iterate over their Object.keys (which is what the snippet console does). (Similarly, the length property of an array does not get displayed, because it's non-enumerable.)
See MDN:
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
Make it enumerable instead:
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
The reason you can see the property in the logged image is that Chrome's console will show you non-enumerable properties as well - but the non-enumerable properties will be slightly greyed-out:
See how age is grey-ish, while name is not - this indicates that name is enumerable, and age is not.
Whenever you use".defineProperty" method of object. You should better define all the properties of the descriptor. Because if you don't define other property descriptor then it assumes default values for all of them which is false. So your console.log checks for all the enumerable : true properties and logs them.
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable : true,
configurable : true
})
console.log(profile)
console.log(profile.age)
I apologize in advance if this has been asked elsewhere or if I have missed something important in the docs, well, but I need to ask this:
Let's say an object is being created without defining the respective properties
cons objA = Object.create({
init(text) {
this.text = text;
}
});
or an object is being created and the respective property has been declared in the properties object
const objB = Object.create({
init(text) {
this.text = text;
}
}, {
text: {
value: '',
writable: true
}
});
I understand that defining properties in the propertiesObject of Object.create helps defining and providing better contracts,
but
do these two scenarios vary in respect to the text property?
Yes, they vary - there is difference between a and b results
const a = Object.create({
init(text) {
this.text = text;
}
});
const b = Object.create({
init(text) {
this.text = text;
}
}, {
text: {
value: '',
writable: true
}
});
console.log(Object.getOwnPropertyNames(a))
console.log(Object.getOwnPropertyNames(b))
a.init('a text');
b.init('b text');
console.log(Object.getOwnPropertyDescriptor(a, 'text'))
console.log(Object.getOwnPropertyDescriptor(b, 'text'))
a returns:
{
"value": "a text",
"writable": true,
"enumerable": true,
"configurable": true
}
b returns:
{
"value": "b text",
"writable": true,
"enumerable": false,
"configurable": false
}
By default property is enumerable and configurable unless you define property by Object.defineProperty or Object.create. You can define them as you did with writable.
Enumerable works in certain object-property enumerations, such as the for..in.
Configurable means that you cannot use Object.defineProperty again on this property (there will be Cannot redefine property: text error).
Other than that - before you use init() - a object will have undefined text property (that is not enumerable, not configurable, writable) and object b will not have any property.
I have been following javascript design patterns and was implementing ES5 properties using the code found at this location.
https://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript
Test 1
Use a function to define 3 properties
Check the values are ok: SUCCESS
Log the object to see if the data looks ok: SUCCESS
Test 2
Use Object.definedProperties to define 3 properties
Check the values are ok: SUCCESS
Log the object to see if the data looks ok: FAIL
Test 1 Code
it('should construct object with some single properites added using helper function', function (done) {
var person = Object.create(Object.prototype);
// Populate the object with properties
pattern.defineProp(person, "car", "Delorean");
pattern.defineProp(person, "dateOfBirth", "1981");
pattern.defineProp(person, "hasBeard", false);
console.log(person.car);
console.log(person);
console.log(typeof person);
console.log(JSON.stringify(person));
person.car.should.equal('Delorean');
person.dateOfBirth.should.equal('1981');
person.hasBeard.should.equal(false);
// Produces
// Delorean
// { car: 'Delorean', dateOfBirth: '1981', hasBeard: false }
// object
// {"car":"Delorean","dateOfBirth":"1981","hasBeard":false}
done();
});
Test 2 Code
it('should construct object with multiple properties using standard ES5 syntax', function (done) {
var person = Object.create(Object.prototype);
// Populate the object with properties
Object.defineProperties(person, {
"car": {
value: "Delorean",
writable: true
},
"dateOfBirth": {
value: "1981",
writable: true
},
"hasBeard": {
value: false,
writable: true
}
});
console.log(person.car);
console.log(person);
console.log(typeof person);
console.log(JSON.stringify(person));
person.car.should.equal('Delorean');
person.dateOfBirth.should.equal('1981');
person.hasBeard.should.equal(false);
// Produces
// Delorean
// {}
// object
// {}
done();
});
Define Prop Function
exports.defineProp = function ( obj, key, value ){
var config = {
value: value,
writable: true,
enumerable: true,
configurable: true
};
Object.defineProperty( obj, key, config );
};
Well, if you are using the standard Object.defineProperties, and omit the enumerable attribute, it will default to false. Your properties won't be displayed because they are not enumerable.
In my Meteor.JS app I declared a Collection:
WPThemes = new Mongo.Collection('wpthemes');
This collection has fixtures that I have inserted.
It has atleast 64 documents in it with the following structure
{
productname: 'sample product name',
name: 'sameple name'
}
I then issue a publication for it:
Meteor.publish('wpthemes', function(options){
check(options, {
limit: Number
});
return WPThemes.find({}, options);
});
In the RouteController I subscribe to it and assign it to the 'data' of the webpage:
WPThemesListController = RouteController.extend({
template: 'wordpress',
increment: 66,
wpthemesLimit: function(){
return parseInt(this.params.wpthemesLimit) || this.increment;
},
findOptions: function(){
return {limit: this.wpthemesLimit()};
},
subscriptions: function(){
this.themesSub = Meteor.subscribe('wpthemes', this.findOptions());
},
themes: function(){
return WPThemes.find({}, this.findOptions());
},
data: function(){
var hasMore = this.themes().count() === this.wpthemesLimit();
return{
themes: this.themes(),
ready: this.themesSub.ready,
nextPath: hasMore ? this.nextPath() : null
}
}
});
So now I'm inside the Template.wordpress.rendered = function(){} block.
I want to access themes as returned in the 'data:' above.
themes gets assigned the value returned by this.themes() and this.themes() gets the value returned by return WPThemes.find({}, this.findOptions());
and as far as i know Collection.find() returns a cursor.
Therefore am I right that themes is holding a cursor object???
When I print to console this.data.themes by: console.log(this.data.themes);
I get this:
[Log] Object (wordpress.js, line 14)
_selectorId: undefined
_transform: null
collection: Object
fields: undefined
limit: 66
matcher: Object
reactive: true
skip: undefined
sorter: null
__proto__: Object
How I iterate over this 'cursor' object and print to the console all of the info stored in the documents?
In this case I want to print every name and product name that was inserted into this collection by:
WPThemes.insert({
productname: stringToUse,
name: studioPressFiles[i]
});
I have inserted atlas 64 documents into this Collection.
And yet, if I do console.log(this.data.themes.count());
I am getting 0....Why is that?
How do I iterate over this cursor to get the data when its supposed items are 0?
The webpage confirms that there are items in the collection because {{#each themes}} works.....
How do I convert this cursor into an array?
Thank you very much...
http://docs.meteor.com/#/full/fetch
So basically all you gotta do is console.log(this.data.themes.fetch());
I have a solution now, but it's not the best I think.
function parseEval(value){
var result = undefined;
try {
result = eval(value);
} catch (e) { }
return result;
}
So if the value is undefined or contains uninterpretable value the function return undefined.
If contains an existing function name than returns function object
if contains "[1,2,3]" then return int array
if contains "[{ label: "Choice1", value: "value1" },{ label: "Choice2", value: "value2" }]" then return an array of objects
I'm open for any solution because the eval has lot of disadvantages. (performance, security, flexibility, maintainability)
If this is an internal function that will never be passed any user-supplied data, this might be the best way to go about things. Otherwise, you would probably be better off using JSON.parse to parse data and look up functions and other non-JSON data in a whitelist:
var someObject = {
aFunction: function() {},
anInt: 42
};
function parse(value) {
var result;
try {
return JSON.parse(value);
} catch(e) {
return someObject[value];
}
}
[{ label: "Choice1", value: "value1" },{ label: "Choice2", value: "value2" }]
isn't json, but assuming that it should be, because you mentioned that in the question,
console.log(typeof JSON.parse(string))
Should work nicely for anything but functions.