4

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?

6
  • 4
    You can use Array.prototype.find() - documentation Commented Mar 11, 2016 at 14:36
  • @AlonEitan I don't doubt there's a duplicate, but I don't think that's it. Commented Mar 11, 2016 at 14:37
  • @Pointy. Thanks. Vote retracted 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 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. Commented Mar 11, 2016 at 14:46

6 Answers 6

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);
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, I believe this is the closest solution that is available.
Make sure you won't break anything in old browsers
@ArseniProkharchyk thanks for the warning, but this code is just for a demonstration and there won't even be a browser in place :)
1

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.

1 Comment

Have to admit, I didn't know about the lib. Though it adds you one more dependancy to your code.. If you are ok with that - do that! Thanks for the lib.
1

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

Comments

1

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

Comments

1

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 comments. It's experimental and supported only Chrome 45+, Safari 7.1+, FF 25+. No IE.

Example can be found here

5 Comments

Can you elaborate and maybe give a small example?
What example would you like me to write? Not sure I understand what you want to see.. Loop? Array.prototype.find? xml XPATH?
Just show OP how to use find or an alternative and give a little information about the support for said method.
do not provide links to external sites as answers, those are not considered answers
The question was "Is this even possible in JavaScript?". I gave my answer. Then, people asked for an example. I provided an example, not considering it as answer, but as a help to find what they are looking for.
0

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

1 Comment

thanks, but I was looking for a pure javascript solution without jquery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.