themadjem
themadjem

Reputation: 43

JSON named objects vs array with name property

This may be a JS question, I'm not sure.

I am using JSON to store data about enemies in a game. I am currently structuring like this:

{
  "Area 1": {
    "Enemy Name": {
      "type": "Human",
      "lvl": 30
    },
    "Enemy 2": {
      "type": "Human",
      "lvl": 30
    }
  },
  "Area 2": {
    "Enemy 1": {
      "type": "Human",
      "lvl": 30
    },
    "Enemy 2": {
      "type": "Human",
      "lvl": 30
    }
  }
}

I was wondering if I should be instead using an array of enemies for each area with a "name" property instead. Like this:

{
  "Area 1": [
    {
      "name": "Enemy Name",
      "type": "Human",
      "lvl": 10
    },
    {
      "name": "Enemy 2",
      "type": "Human",
      "lvl": 30
    }
  ],
  "Area 2": [
    {
      "name": "Enemy 1",
      "type": "Human",
      "lvl": 30
    },
    {
      "name": "Enemy 2",
      "type": "Human",
      "lvl": 30
    }
  ]
}

I believe the second is the way I should be doing it but wanted other's feedback. I think with the first way, I'll need to know the names of the enemies in order to read their data whereas, with the array, I can loop through the areas and read the enemies in each area. Thanks in advance for any help!

Upvotes: 4

Views: 15483

Answers (1)

Edison D'souza
Edison D'souza

Reputation: 4640

The second option feels right. It is properly structured and you can easily loop through any Area to perform operations on Enemies. My suggestion is to go with second one.

var Map = [
  Area1: [
    {
      name: "Enemy 1";
      metaData: '...'
    },
    {
      name: "Enemy 2";
      metaData: '...'
    }
  ],
  Area2: [
    {
      name: "Enemy 1";
      metaData: '...'
    }
  ]
];

Scanning enemies in particular area.

Map[Area1].forEach(function(enemy) {
  //Operation ...
});

I hope this helps. :)

Upvotes: 2

Related Questions