-1

I created an object in JavaScript and stored some information in the object. I searched a lot for solution, but did not find any solution. I want to get the count/length of object.

Javascript Code:
productDetail = new Object();
productDetail["Code"] = "A104";
productDetail["ProductName"] = "Keyboard";
productDetail["UnitPrice"] = 10;
productDetail["Dealer"] = "AMD";
Faseeh Haris
  • 669
  • 1
  • 11
  • 29
  • 1
    What about nested object? What about array inside of that object? Did `Object.keys().length` not work for you? – Chau Tran Feb 24 '20 at 19:37
  • Thanks, worked for me. very quick solution. – Faseeh Haris Feb 24 '20 at 19:39
  • Your question starts with: _I have a JavaScript object, is there a built-in or accepted best practice way to get the length of this object?_. The one from 2008 starts with: _I have a JavaScript object, is there a built-in or accepted best practice way to get the length of this object?_. The exact same 111 characters. What are the odds? – mbojko Feb 24 '20 at 19:44

1 Answers1

1

This is what you are looking for:

Object.keys(productDetail).length

You are after the count of the property keys of the object.

const productDetail = new Object();
productDetail["Code"] = "A104";
productDetail["ProductName"] = "Keyboard";
productDetail["UnitPrice"] = 10;
productDetail["Dealer"] = "AMD";

console.log(Object.keys(productDetail).length)
Josh Wulf
  • 4,727
  • 2
  • 20
  • 34