0

working through a large json that has multiple arrays that can move around in order.

{
  "person": {
    "Clark": [
      {
        "lastName": "Kent",
        "job": "Reporter",
        "roll": 20,
        "weaknesses": [
          "kryptonite",
          "Lois"
        ]
      },
      {
        "alterEgo": "Superman",
        "powers": [
          "strength",
          "lasereyes",
          "hair"
        ]
      }
    ],
    "Bruce": [
      {
        "lastName": "Wayne",
        "job": "Playboy",
        "roll": 30,
        "weaknesses": [
          "cats",
          "clowns"
        ]
      },
      {
        "alterEgo": "Batman",
        "powers": [
          "fighting",
          "gadgets",
          "money"
        ]
      }
    ],
    "Peter": [
      {
        "alterEgo": "Spiderman",
        "powers": [
          "strength",
          "arm-goo",
          "wit"
        ],
        "weaknesses": [
          "midterms",
          "girls"
        ]
      },
      {
        "lastName": "Parker",
        "job": "Photographer",
        "roll": 40
      }
    ]
  }
}

The powers and / or weaknesses each move around and either could be in [0] sometimes [1] sometimes [53] etc. How can I search for persons[0].weakness if if I don't know which array its in? I know its there just don't know where. Thanks for the time.

thinguy
  • 53
  • 7
  • 1
    No magical solution, you have to loop over the items (the persons) and to test each of them. – Casimir et Hippolyte Jun 28 '21 at 20:07
  • Thanks. thats what I'm missing how to do. The persons[i] with i being a loop? but if person[0].weakness doesn't exist I'm not sure how to deal with the error handling. – thinguy Jun 28 '21 at 21:10
  • Use [hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty), if the `weakness` property doesn't exist continue to the next item. – Casimir et Hippolyte Jun 28 '21 at 21:17
  • Looks also at @Ntwari Clarance Liberiste answer in this [post](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-specific-property-in-javascript), there are insteresting alternatives to `hasOwnProperty`. – Casimir et Hippolyte Jun 28 '21 at 21:24

0 Answers0