1

I am pretty much new in Angular. I have a json file. I want to get the value of "ciena" based on the input provided by user. Say if user provides 'ciena' then I should get the json for ciena only. I can not use the position like below because I am not sure about the input provided by user.

import * as familyNames from '../../../assets/jsonFiles/deviceFamilyList.json';

---> this.families = familyNames['families'][0]; --this will not work in my case.

{
    "families": [
        {
            "**ciena**" : [
                {"name": "Waveserver Family"},
                {"name": "6500 Family"},
                {"name": "5400 Family"},
                {"name": "Z-Series"},
                {"name": "3000 Family"},
                {"name": "5000 Family"},
                {"name": "6500 PTS"},
                {"name": "8180"},
                {"name": "8700"},
                {"name": "Pluggable Transceiver Family"}
            ]
        },
        {
            "**huawei**": []
        }
    ]
}

So to get the particular json value of ciena or huawei from the json file what can I do in .ts file? I am using Angular 8.

Thanks in advance for help! :)

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Surya
  • 604
  • 1
  • 6
  • 25
  • Does this answer your question? [Angular 5 Service to read local .json file](https://stackoverflow.com/questions/47206924/angular-5-service-to-read-local-json-file) – Prashant Pimpale Jan 27 '20 at 08:43

1 Answers1

2

Simply use:

let searchVar = '**huawei**';
const obj = this.familyNames.families
                .filter(e => Object.keys(e).find(i => i === searchVar));
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • This throw error if the json does not start with families always. Is there any other method or Observable is the next choice ? – Sats Jan 27 '20 at 09:06
  • This will not throw any error. If the key is not found then you get an empty array. – Nicholas K Jan 27 '20 at 09:08
  • I mean inside the json, if the json is not having "families" – Sats Jan 27 '20 at 09:09
  • 1
    From what I understand, it looks like `families` will always be present. However, if OP isn't sure then a simple check can be done before the search operation i.e `const obj = this.familyNames && ..... ;` – Nicholas K Jan 27 '20 at 09:12