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

时间:2016-03-11 14:34:53

标签: javascript arrays json

我有以下JSON:

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

我想使用"value"访问数组元素的"fieldName": "telNum"而不使用索引号,因为我不知道每次都会确切地显示此telNum元素的位置。< / p>

我梦想的是这样的事情:

jsonVarName .responseObject.fields [ '字段名'= 'telNum']。值

这在JavaScript中是否可行?

6 个答案:

答案 0 :(得分:3)

你可以这样做

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);

答案 1 :(得分:1)

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

可以找到示例here

答案 2 :(得分:1)

JSONPath可以让你像XPATH一样编写查询。

$.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.

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

你必须循环找到它。

&#13;
&#13;
SwingWorker
&#13;
&#13;
&#13;

答案 5 :(得分:0)

只需循环遍历数组的简洁方法。

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
    }
  })