最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to access a json array element without using index number? - Stack Overflow

programmeradmin2浏览0评论

I have the following JSON:

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

I want to access "value" of the the array element with "fieldName": "telNum" without using index numbers, because I don't know everytime exactly at which place this telNum element will appear.

What I dream of is something like this:

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

Is this even possible in JavaScript?

I have the following JSON:

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

I want to access "value" of the the array element with "fieldName": "telNum" without using index numbers, because I don't know everytime exactly at which place this telNum element will appear.

What I dream of is something like this:

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

Is this even possible in JavaScript?

Share Improve this question edited Mar 11, 2016 at 17:30 user177800 asked Mar 11, 2016 at 14:34 schlingelschlingel 1,6943 gold badges19 silver badges29 bronze badges 6
  • 4 You can use Array.prototype.find() - documentation – Pointy Commented Mar 11, 2016 at 14:36
  • @AlonEitan I don't doubt there's a duplicate, but I don't think that's it. – Pointy Commented Mar 11, 2016 at 14:37
  • @Pointy. Thanks. Vote retracted – Alon Eitan Commented Mar 11, 2016 at 14:37
  • 1 Possible duplicate of Javascript - get the value of a property within a specific JSON array element by its key – user177800 Commented Mar 11, 2016 at 14:39
  • 1 If you are in control of generating the JSON, I would suggest you pick a different layout, and use the fieldName-value as an objectKey instead of an array value. – Soren Commented Mar 11, 2016 at 14:46
 |  Show 1 more ment

6 Answers 6

Reset to default 4

You can do it like this

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

There is JSONPath that lets you write queries just like XPATH does for 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.

You will have to loop through and find it.

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

It might be a better option to modify the array into object with fieldName as keys once to avoid using .find over and over again.

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

It's not possible.. Native JavaScript has nothing similar to XPATH like in xml to iterate through JSON. You have to loop or use Array.prototype.find() as stated in ments. It's experimental and supported only Chrome 45+, Safari 7.1+, FF 25+. No IE.

Example can be found here

Clean and easy way to just loop through array.

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
    }
  })
发布评论

评论列表(0)

  1. 暂无评论