Reputation: 20856
Im trying to find the length of the report_data(object) key using the below code..but for some reasons it yields value 3.
a={report_freq: "daily", report_item_num: 2, report_num: 39, report_data: "{}"}
Object {report_freq: "daily", report_item_num: 2, report_num: 39, report_data: "{}"}
Object.getOwnPropertyNames(a.report_data).length
3
for more clarity I have the image.
Upvotes: 0
Views: 156
Reputation: 25820
a.report_data
is a string with three properties:
0
, representing the first character ("{"
).
1
, representing the second character ("}"
).
and length
, representing the length of the string (2
).
It's a little counter-intuitive, if you come from other languages, that 0
and 1
are properties, but in Javascript array elements are properties just like all other properties, and "regular" properties can be accessed using array syntax (aka "bracket notation"):
// "array elements"
a.report_data[0] === "{";
a.report_data[1] === "}";
// or...
a.report_data["0"] === "{";
a.report_data["1"] === "}";
// "normal" properties
a.report_data.length === 2;
// or...
a.report_data["length"] === 2;
These are all property names, and, thus, when you ask for an array of property names for your string, you get:
["0", "1", "length"]
Upvotes: 6
Reputation: 39649
Assuming you want the length of the actual string value, then you simply want to use report_data.length
, as demonstrated here:
var a = {
report_freq: "daily",
report_item_num: 2,
report_num: 39,
report_data: "{}"
};
console.log(a.report_data.length)
Your current code includes this:
Object.getOwnPropertyNames(a.report_data).length
If you look at the docs for Object.getOwnPropertyNames(obj)
, you'll see the following description:
Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly upon obj.
So, in this case, Object.getOwnPropertyNames(a.report_data)
returns an array containing the keys found on the string, and there happens to be 3 of them.
Upvotes: 0