按键选择JSON数组对象

use*_*559 2 javascript arrays json

我有JSON数组看起来像

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
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

再往下我试着这样做:

  1. 访问fieldNamefirstName对象.不使用索引就可以做到吗?

data.fields给了我一个对象数组.从那以后,我似乎无法使用对象密钥访问.

另外,data.fields[0]给出整个firstName对象,但我似乎无法做data.fields[0]["field"]data.fields[0].field

谢谢.

Cer*_*nce 5

您可以.find用来查找数组中的特定元素:

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);
Run Code Online (Sandbox Code Playgroud)

另请注意,您没有 "JSON数组".JSON是将对象表示为字符串表示法.你只有一个普通的对象.

如果您将fields对象变为对象而不是数组,您可能会发现它更容易,例如:

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
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以直接访问属性,例如,data.fields.firstName无需借助.find.