0

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.

enter image description here

4
  • You mean keys of json object? Commented Jan 10, 2017 at 19:06
  • 4
    report_data is a string, not an object Commented Jan 10, 2017 at 19:06
  • 1
    even if its a string..WHy does it yield a value of 3? Commented Jan 10, 2017 at 19:09
  • JDB answered your question below :) Commented Jan 10, 2017 at 19:10

2 Answers 2

6

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"]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.