简体   繁体   中英

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

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

You can use below approach -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM