0

I'm working with json objects in typescript for the first time.

I have an object like this:

[
    {
        "e_name": "fake_c",
        "fields": [
            {
                "field_name": "c_name",
                "title": "C Name",
                "control_name": "cname"
            },
            {
                "field_name": "c_address",
                "title": "C Address",
                "control_name": "caddress"            
    },
            {
                "field_name": "c_number",
                "title": "C Number",
                "control_name": "cnumber"
            }
        ]
    },
    {
        "e_name": "fake_b",
        "fields": [
            {
                "field_name": "b_name",
                "title": "B Name",
                "control_name": "bname"
            },
            {
                "field_name": "b_address",
                "title": "B Address",
                "control_name": "baddress"
            },
            {
                "field_name": "b_number",
                "title": "B Number",
                "control_name": "bnumber"
            }
        ]
    }
]

I'm trying to build an array of objects using this mapping json, based on a value of e_name passed through.

I essentially want to reference the part of my json where the e_name is equal to the passed through variable, name.

From there, I am going to loop through the fields records and push to other arrays.

So for example, if name="fake_c", I will loop through the 3 fields objects under "fake_c".

How do I access this section of the json object?

I have tried accessing by:

this.json_map(name);

I wasn't expecting this to work but I'm not sure how I can access based on the key value.

Maybe I need to change the json format?

nimgwfc
  • 1,294
  • 1
  • 12
  • 30

2 Answers2

1

Simple solution to achieve what you required could be:

function getFieldsByname(name: string) {
  return data.filter((d)=> d.e_name === name).map((res) => res.fields)
}

const fields = getFieldsByname('fake_c');
console.log(fields)

P.S: data is your JSON object.

Working DEMO

Kamran Khatti
  • 3,754
  • 1
  • 20
  • 31
0

Find the relevant object in the array, then retrieve fields array via map operation.

const getFields = (name) => data.find(element => element.e_name === name).map(item => item.fields)

Then just use a forEach loop to iterate:

getFields("xxx").forEach(field => {..logic here});
Berk Kurkcuoglu
  • 1,453
  • 1
  • 9
  • 11