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

Time:08-26

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"}]))

CodePudding user response:

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']);
 }

CodePudding user response:

You can use below approach -

function getNames(names) {
      return (names || []).filter((singleUser) => singleUser.name)
                          .map((singleUser) => singleUser.name);
}
  • Related