Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting array of school values from all objects using JS

Hello I am new to the JavaScript language.

I have a table1.data property that’s an array of objects with data about a school like:

{ schoolName: "School 1", telephone: "123456", address: "1st street, 1st road" }

Can I perhaps get an array of the telephone values from all the objects using JS? Please help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

All you need to do it traverse the items in the data, while grabbing the telephone field value.

Here is the long-way:

const table1 = {
  data: [
    { schoolName: "School 1", telephone: "(111) 111-1111", address: "1st street" },
    { schoolName: "School 2", telephone: "(222) 222-2222", address: "2nd street" },
    { schoolName: "School 3", telephone: "(333) 333-3333", address: "3rd street" }
  ]
};

const phoneNumbers = [];
for (let i = 0; i < table1.data.length; i++) {
  phoneNumbers.push(table1.data[i].telephone);
}

console.log(phoneNumbers);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Here is the short way:

const table1 = {
  data: [
    { schoolName: "School 1", telephone: "(111) 111-1111", address: "1st street" },
    { schoolName: "School 2", telephone: "(222) 222-2222", address: "2nd street" },
    { schoolName: "School 3", telephone: "(333) 333-3333", address: "3rd street" }
  ]
};

const phoneNumbers = table1.data.map(({ telephone }) => telephone);

console.log(phoneNumbers);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading