是否可以在不使用索引号的情况下访问 json 数组元素

Is it possible to access a json array element without using index number?

本文关键字:情况下 访问 数组元素 json 索引 是否      更新时间:2023-09-26

我有以下JSON:

{
   "responseObject": {
   "name": "ObjectName",
   "fields": [
   {
     "fieldName": "refId",
     "value": "2170gga35511"
   },
   {
     "fieldName": "telNum",
     "value": "4541885881"
   }]}
}

我想在不使用索引号的情况下访问带有"fieldName": "telNum"数组元素的"value",因为我不知道每次这个telNum元素会出现在哪个位置。

我的梦想是这样的:

jsonVarName.responseObject.fields['fieldname'='telNum'].value

这在 JavaScript 中可能吗?

你可以这样做

var k={
   "responseObject": {
   "name": "ObjectName",
   "fields": [
   {
     "fieldName": "refId",
     "value": "2170gga35511"
   },
   {
     "fieldName": "telNum",
     "value": "4541885881"
   }]
}};
value1=k.responseObject.fields.find(
function(i)
{return (i.fieldName=="telNum")}).value;
console.log(value1);

有一个JSONPath,可以让你像XPATH对XML一样编写查询。

$.store.book[*].author  the authors of all books in the store
$..author               all authors
$.store.*               all things in store, which are some books and a red bicycle.
$.store..price          the price of everything in the store.
$..book[2]              the third book
$..book[(@.length-1)] 
$..book[-1:]            the last book in order.
$..book[0,1]
$..book[:2]             the first two books
$..book[?(@.isbn)]      filter all books with isbn number
$..book[?(@.price<10)]  filter all books cheapier than 10
$..*                    All members of JSON structure.

你将不得不循环并找到它。

var json = {
   "responseObject": {
   "name": "ObjectName",
   "fields": [
   {
     "fieldName": "refId",
     "value": "2170gga35511"
   },
   {
     "fieldName": "telNum",
     "value": "4541885881"
   }]
};
  
function getValueForFieldName(fieldName){
  for(var i=0;i<json.fields.length;i++){
    if(json.fields[i].fieldName == fieldName){
      return json.fields[i].value;
    }
  }
  return false;
}
console.log(getValueForFieldName("telNum"));

数组修改为以fieldName作为键的对象可能是一个更好的选择,以避免一遍又一遍地使用.find

fields = Object.assign({}, ...fields.map(field => {
    const newField = {};
    newField[field.fieldName] = field.value;
    return newField;
}

是不可能的。原生 JavaScript 没有类似于 xml 中的 XPATH 来迭代 JSON。您必须按照注释中所述循环或使用Array.prototype.find()。它是实验性的,仅支持Chrome 45 +,Safari 7.1 +,FF 25 +。没有IE。

示例可在此处找到

干净简单的方法来循环数组。

var json = {
   "responseObject": {
   "name": "ObjectName",
   "fields": [
    {
     "fieldName": "refId",
     "value": "2170gga35511"
    },
  {
    "fieldName": "telNum",
    "value": "4541885881"
  }]
 }   
  $(json.responseObject.fields).each(function (i, field) {
    if (field.fieldName === "telNum") {
      return field.value // break each
    }
  })