[英]Pick JSON array object by its key
I have JSON array that looks like 我有看起来像的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
}
}
]
}
Further down I am trying to do this: 再往下,我正在尝试这样做:
fieldName
of the firstName object. 访问firstName对象的fieldName
。 Is there to do that without using the index? 不用索引就可以做到吗? data.fields
gives me the array of object. data.fields
给了我对象数组。 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
另外, data.fields[0]
给出了整个firstName对象,但我似乎无法做data.fields[0]["field"]
或data.fields[0].field
Thanks. 谢谢。
You can use .find
to find a particular element in an array: 您可以使用.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);
Also note that you do not have a "JSON array". 另请注意,您没有 “ JSON数组”。 JSON is a notation for representing objects as strings . JSON是一种用于将对象表示为字符串的表示法 。 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: 如果将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
}
}
};
Then you could access the properties directly with, for example, data.fields.firstName
without having to resort to .find
. 然后,您可以使用例如data.fields.firstName
直接访问属性,而不必诉诸.find
。
data.fields[0]
is this object data.fields[0]
是此对象
{
"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. 因此,如果您要访问该对象中属于firstName
键的任何内容,则无需使用索引,因为它是一个对象而不是数组。 You can access it like data.fields[0].firstName
which will be equal to 您可以像data.fields[0].firstName
一样访问它,它等于
{
"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 此外,如果要访问内部字段/属性,请执行data.fields[0].firstName.fieldName
等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.