-2

how to get object length in pure javascript in this code

let myFavGames = {
  "Trinity Universe": {
    publisher: "NIS America",
    price: 40,
  },
  "Titan Quest": {
    publisher: "THQ",
    bestThree: {
      one: "Immortal Throne",
      two: "Ragnarök",
      three: "Atlantis",
    },
    price: 50,
  },
  YS: {
    publisher: "Falcom",
    bestThree: {
      one: "Oath in Felghana",
      two: "Ark Of Napishtim",
      three: "origin",
    },
    price: 40,
  },
};

// Code One => How To Get Object Length ?
let objectLength = ?;
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
imad
  • 1
  • 1
    Please explain in your post what you mean when you say "object length", because that's not a thing in JS (objects have no length property). Also, remember to have a look at [all the Object utility functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), because you'll discover a _lot_ of things that you can do with objects. – Mike 'Pomax' Kamermans Mar 20 '22 at 16:20
  • 1
    Does [this](https://stackoverflow.com/a/6700/128761) help? (In your case, use `Object.keys(myFavGames).length;`.) – vee Mar 20 '22 at 16:20

2 Answers2

0

You can use Object.keys() to get the number of keys in your object:

const myFavGames = {
  "Trinity Universe": {
    publisher: "NIS America",
    price: 40,
  },
  "Titan Quest": {
    publisher: "THQ",
    bestThree: {
      one: "Immortal Throne",
      two: "Ragnarök",
      three: "Atlantis",
    },
    price: 50,
  },
  YS: {
    publisher: "Falcom",
    bestThree: {
      one: "Oath in Felghana",
      two: "Ark Of Napishtim",
      three: "origin",
    },
    price: 40,
  },
};

const objectLength = Object.keys(myFavGames).length;
console.log(objectLength); // 3
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
0

The Object.keys() method returns an array of a given object's own enumerable property names.

console.log(Object.keys(myFavGames).length);