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

Looking to open out an array of objects into new object as strings Javascript

Still trying to get to grips with coding, I have this question I’m trying to answer and can’t quite work it out. I’m looking to take an array of objects and then return all of the users names in a new array as strings. Can anyone help? cheers

function getNames(names) {

  let newArray = [];

  for(let i = 0; i < names.length; i++){
    if(names[i] == names.hasOwnProperty[name]){
      newArray.push(names[name]);
    } 
  } return newArray;
}

console.log(getNames([{name: "Pete", age: 35, language: "Javascript"},{name: "John", age: 40, language: "Javascript"}, {name:"Carol", age: 30, language: "Javascript"}]))

>Solution :

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

When you loop names, names[i] is the object, and names[i]['name'] is the name.

function getNames(names) {

  let newArray = [];

  for(let i = 0; i < names.length; i++){
      newArray.push(names[i]['name']);
  } 

  return newArray;
}

If you are not sure the object has name property, you may check it:

 if (names[i].hasOwnProperty['name']){
      newArray.push(names[i]['name']);
 }
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