Skip to content
Advertisement

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.

Advertisement

Answer

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; }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement