user3861559
user3861559

Reputation: 993

Pick JSON array object by its key

I have JSON array that looks like

var data = {
  "fields": [{
      "firstName": {
        "fieldName": "First Name",
        "required": true,
        "provided": false
      }
    },
    {
      "lastName": {
        "fieldName": "Last Name",
        "required": true,
        "provided": false
      }
    },
    {
      "email": {
        "fieldName": "Email",
        "required": true,
        "provided": false
      }
    }
  ]
}

Further down I am trying to do this:

  1. Access the fieldName of the firstName object. Is there to do that without using the index?

data.fields gives me the array of object. From there onwards, I do not seem to be able to access with the object key.

Also, data.fields[0] gives the whole firstName object but I can't seem to do data.fields[0]["field"] or data.fields[0].field

Thanks.

Upvotes: 2

Views: 286

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371168

You can use .find to find a particular element in an array:

var data={"fields":[{"firstName":{"fieldName":"First Name","required":!0,"provided":!1}},{"lastName":{"fieldName":"Last Name","required":!0,"provided":!1}},{"email":{"fieldName":"Email","required":!0,"provided":!1}}]}
const firstNameFieldName = data.fields
  .find(obj => 'firstName' in obj)
  .firstName.fieldName;
console.log(firstNameFieldName);

Also note that you do not have a "JSON array". JSON is a notation for representing objects as strings. You just have a plain object.

You might find it easier if you turned the fields into an object instead of an array, such as:

var data = {
  fields: {
    "firstName": {
      "fieldName": "First Name",
      "required": true,
      "provided": false
    },
    "lastName": {
      "fieldName": "Last Name",
      "required": true,
      "provided": false
    },
    "email": {
      "fieldName": "Email",
      "required": true,
      "provided": false
    }
  }
};

Then you could access the properties directly with, for example, data.fields.firstName without having to resort to .find.

Upvotes: 5

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22925

data.fields[0] is this object

{
    "firstName": {
        "fieldName": "First Name",
        "required": true,
        "provided": false
    }
}

So if you want to access anything indide that object which is firstName key, you don't need to use index because it is an Object and not an Array. You can access it like data.fields[0].firstName which will be equal to

{
    "fieldName": "First Name",
    "required": true,
    "provided": false
}

And further if you want to access inner fields/properties, do data.fields[0].firstName.fieldName and so on

Upvotes: 1

Related Questions