Home > Back-end >  Getting array of school values from all objects using JS
Getting array of school values from all objects using JS

Time:09-01

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.

CodePudding user response:

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; }

CodePudding user response:

Why not use a for loop

let data = [
  {schoolName: "School 1", telephone: "123456", address: "1st street, 1st road"},
  {schoolName: "School 2", telephone: "654321", address: "2nd street, 2nd road"}
];

let telephoneArr = [];
for (const addressObj of data) {
   telephoneArr.push(addressObj.telephone);
};
console.log(telephoneArr);

Or you could use Object.keys

let data = [
  {schoolName: "School 1", telephone: "123456", address: "1st street, 1st road"},
  {schoolName: "School 2", telephone: "654321", address: "2nd street, 2nd road"}
];

let telephoneArr = [];
data.forEach(school => Object.keys(school).forEach(function(key, index) {
  if (key === 'telephone') telephoneArr.push(school[key]);
}));

console.log(telephoneArr);

CodePudding user response:

You can use the javascript map function which creates a new array by calling a function for every array element.

let table1 = [{ schoolName: "School 1", telephone: "123456", address: "1st street, 1st road" },
{ schoolName: "School 2", telephone: "654321", address: "2nd street, 2nd road" },
{ schoolName: "School 1", telephone: "321654", address: "3rd street, 3rd road" }];

//new empty array that will hold th phone numbers
const phoneNumbers = [];

table1.map(({telephone})=>{
//populate the phoneNumbers array with phone numbers by iterating the initial array
phoneNumbers.push(telephone)
})

console.log(phoneNumbers)

  • Related