-2

I am trying to parse an object which contains arrays. I need the object where language is "en",

    "translations": [
        {"languageCode": "id","value": "Program Televisi"},
        {"languageCode": "ms","value": ""}, 
        {"languageCode": "ar","value": "تليفزيون"},
        {"languageCode": "en","value": "Television"}
    ]
},
"subgenre": {
    "id": 227,
    "translations": [
        {"languageCode": "id","value": "Sports"},
        {"languageCode": "ms","value": ""}, 
        {"languageCode": "ar","value": ""},
        {"languageCode": "en","value": "Sports"}
    ]
}

I don't want to do it this way :

translations_array.forEach(function (obj1, i) {
  if (obj1.languageCode === 'en') {
    return obj1.value.toString();
  }                        
});

Instead I'd rather something like fetching directly:

translations[].value[languageCode='en']
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Mohit H
  • 927
  • 3
  • 11
  • 26
  • 1
    FYI nothing about this has anything to do with JSON. I've amended the question and title accordinly – Rory McCrossan Sep 01 '17 at 11:35
  • ...and the better layout shows you've mised the id and key of that first array. Doesnt affect the answer. – Jamiec Sep 01 '17 at 11:36
  • @Jamiec: I assume you've found a better duplicate target? – Cerbrus Sep 01 '17 at 11:36
  • @Cerbrus no, but I can tell you the one that was chosen was terrible and nothing to do with this question or its answer. – Jamiec Sep 01 '17 at 11:37
  • So, do a quick search to find a proper target, instead of opening this for more answers... – Cerbrus Sep 01 '17 at 11:37
  • @Cerbrus I have and I am. Calm yourself. There is no harm in this getting other answers. And having your question closed with a pointless duplicate is just annoying for newer users – Jamiec Sep 01 '17 at 11:38
  • There is harm: We don't want to give users the idea it's okay to answer obvious duplicates. Those answers prevent the Roomba from doing its job. Just like the upvoted answer on here is not preventing this question from being auto-deleted. – Cerbrus Sep 01 '17 at 11:39
  • btw, why is there a return value in `forEach`? – Nina Scholz Sep 01 '17 at 11:40

1 Answers1

1

Use Array.find :

let languageObj = translations.find( obj => obj.languageCode === 'en')
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63