0

I am trying to read the following api json response in typescript. I have tried by defining interfaces as shown below. But when reading the values of phone number using loops I am getting value as undefined.

Could some one please help me to parse the below json file in most efficient way.

    for(let i=0; i < custdetails.length; i++){
       phnnumber[i] = custdetails[i].phoneNumber;
    }

export interface Address {
    streetAddress: string;
    city: string;
}

export interface PhoneNumber {
    type: string;
    number: string;
}

export interface custdetails{
    name: string;
    age: number;
    address: Address[];
    phoneNumber: PhoneNumber[];
}

    [
      {
            "name": "Test name1",
            "age": 30,
            "address": {
                "streetAddress": "2nd test street",
                "city": "London"
            },
            "phoneNumber": [{
                    "type": "home",
                    "number": "111 111-1111"
                },
                {
                    "type": "fax",
                    "number": "222 222-2222"
                }
            ]
        },
        {
            "name": "Test name2",
            "age": 30,
            "address": {
                "streetAddress": "3rd test street",
                "city": "Sydney"
            },
            "phoneNumber": [{
                    "type": "home",
                    "number": "888 888-8888"
                },
                {
                    "type": "fax",
                    "number": "999 999-9999"
                }
            ]
        }
    ]
8
  • This is NOT a JSON file/text string; this is a JavaScript Object json.org/json-en.html and an object: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - given what you show we have to assume it has already been parsed from a JSON string that was received? Commented Jul 22, 2022 at 17:21
  • 1
    What is rootobjarray? If it's the result of parsing the JSON shown, it would be an array of custdetails. That object's phoneNumber property is an array of PhoneNumber objects (and should probably be named phoneNumber**s**. So phnnumber[i] will be an array of PhoneNumber objects. It's not clear what's undefined... Commented Jul 22, 2022 at 17:25
  • Hi Heretic, I have misspelled variables. basically I am looking to create an array with list of phone numbers phoneNumbers : string[] = [] console.log(phoneNumbers) should give [111 111-1111, 222 222-2222, 888 888-8888, 999 999-9999] Commented Jul 22, 2022 at 17:33
  • try changing custdetails to Custdetails.. C in interface to be capital.. I believe you mistyped it Commented Jul 22, 2022 at 17:34
  • @AdityaParab, yes I have misspelled variables sorry ab that basically I am looking to create an array with list of phone numbers phoneNumbers : string[] = [] console.log(phoneNumbers) should give [111 111-1111, 222 222-2222, 888 888-8888, 999 999-9999] Commented Jul 22, 2022 at 17:36

4 Answers 4

1

You'd simply need to map over the object and extract necessary information. Since, your phoneNumber is an array located within an array of objects, you'd need to use .flatMap.

const customerDetails = [
  {
    name: 'Test name1',
    age: 30,
    address: {
      streetAddress: '2nd test street',
      city: 'London',
    },
    phoneNumber: [
      {
        type: 'home',
        number: '111 111-1111',
      },
      {
        type: 'fax',
        number: '222 222-2222',
      },
    ],
  },
  {
    name: 'Test name2',
    age: 30,
    address: {
      streetAddress: '3rd test street',
      city: 'Sydney',
    },
    phoneNumber: [
      {
        type: 'home',
        number: '888 888-8888',
      },
      {
        type: 'fax',
        number: '999 999-9999',
      },
    ],
  },
];

const phoneNumbers = customerDetails
  .flatMap((customer) => customer.phoneNumber.map((pn) => pn.number));

console.log(phoneNumbers); // [ '111 111-1111', '222 222-2222', '888 888-8888', '999 999-9999' ]
Sign up to request clarification or add additional context in comments.

Comments

0

We cannot create the object of interface. Instead of interface use class as shown below:

export class Address {
    streetAddress: string;
    city: string;
}

export class PhoneNumber {
    type: string;
    number: string;
}

export class custdetails{
    name: string;
    age: number;
    address: Address[];
    phoneNumber: PhoneNumber[];
}

And I will recommend to initialize the class property using constructor, so that you should not get undefined.

1 Comment

Interface is perfectly valid for this, class is not necessary and overkill.
0

first define your model like this,

export class Address {
  constructor(streetAddress: string,
              city: string) {}
}

export class PhoneNumber {
  constructor(type: string,
              number: string) {}
}

export class custdetails {
  constructor(
    name: string,
    age: number,
    address: Address[],
    phoneNumber: PhoneNumber[]
  ) {}
}

second, in another class(Datasource class) define values for customer details like this,

export class Datasource {
customerDetails: custdetails =
  [
    {
          "name": "Test name1",
          "age": 30,
          "address": {
              "streetAddress": "2nd test street",
              "city": "London"
          },
          "phoneNumber": [{
                  "type": "home",
                  "number": "111 111-1111"
              },
              {
                  "type": "fax",
                  "number": "222 222-2222"
              }
          ]
      },
      {
          "name": "Test name2",
          "age": 30,
          "address": {
              "streetAddress": "3rd test street",
              "city": "Sydney"
          },
          "phoneNumber": [{
                  "type": "home",
                  "number": "888 888-8888"
              },
              {
                  "type": "fax",
                  "number": "999 999-9999"
              }
          ]
      }
  ]
}

phoneNumbers = customerDetails .flatMap((customer) => customer.phoneNumber.map((phone) => phone.number));

Comments

0

Use map in order to extract the "number" from "phoneNumber"

var phnnumbers = []
for(let i=0; i < custdetails.length; i++){
    phnnumbers = phnnumber.concat(custdetails[i].phoneNumber.map(phone => phone.number))
}

2 Comments

This won't work. .concat doesn't modify original array. You'd need to do phnnumber = phnnumber.concat(....;
You are right. I will correct my answer. Thank you!

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.