最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to return an array as an array of objects? - Stack Overflow

programmeradmin2浏览0评论

I have the following exercise:

  • Write a function called createListOfObjects that accepts an
  • an array of strings with first and last names and returns
  • an array of objects that each have the property firstName
  • and lastName and first name and last name values
  • corresponding value *
  • var namesList = ['Cameron Betts', 'Shana Lopez', 'Angela Li'] *
  • createListOfObjects(namesList)
  • =>
  • [
  • { firstName: 'Camer', lastName: 'Betts'},
  • { firstName: 'Shana', lastName: 'Lopez'},
  • { firstName: 'Angela', lastName: 'Li'}
  • ]

And my solution until now:

createListOfObjects = () => {
    let names = ['Cameron Betts', 'Shana Lopez', 'Angela Li'];

  let deck = [];

    for (var i=0; i < names.length; i++){
      for (var k=0; k < names.length; k++){
  deck.push({ fName: names[i], lName: names[k]})
      }
    };
    return deck;
}

console.log(createListOfObjects());

But it returns the following:

I have to extract the names from the array and then split them to use in my for but I can't understand how exactly I can do that.

I have the following exercise:

  • Write a function called createListOfObjects that accepts an
  • an array of strings with first and last names and returns
  • an array of objects that each have the property firstName
  • and lastName and first name and last name values
  • corresponding value *
  • var namesList = ['Cameron Betts', 'Shana Lopez', 'Angela Li'] *
  • createListOfObjects(namesList)
  • =>
  • [
  • { firstName: 'Camer', lastName: 'Betts'},
  • { firstName: 'Shana', lastName: 'Lopez'},
  • { firstName: 'Angela', lastName: 'Li'}
  • ]

And my solution until now:

createListOfObjects = () => {
    let names = ['Cameron Betts', 'Shana Lopez', 'Angela Li'];

  let deck = [];

    for (var i=0; i < names.length; i++){
      for (var k=0; k < names.length; k++){
  deck.push({ fName: names[i], lName: names[k]})
      }
    };
    return deck;
}

console.log(createListOfObjects());

But it returns the following:

I have to extract the names from the array and then split them to use in my for but I can't understand how exactly I can do that.

Share Improve this question asked Nov 23, 2018 at 0:42 Enrique VargasEnrique Vargas 1594 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

One option would be to split each full name, so as to have the first and last name, and then you can create an object from those two variables. Ideally, use .map for this - .map is the most appropriate method for transforming every element in one array into another array:

createListOfObjects = names => names.map((name) => {
  const [firstName, lastName] = name.split(' ');
  return { firstName, lastName };
});
console.log(createListOfObjects(['Cameron Betts', 'Shana Lopez', 'Angela Li']));

To fix your existing code, you would need to iterate over names only once (no nested loops), and on each iteration, split the name string, and push to deck:

const createListOfObjects = () => {
  let names = ['Cameron Betts', 'Shana Lopez', 'Angela Li'];
  let deck = [];

  for (var i=0; i < names.length; i++){
    const fullName = names[i];
    const nameArray = names[i].split(' ');
    const fName = nameArray[0];
    const lName = nameArray[1];
    for (var k=0; k < names.length; k++){
      deck.push({ fName, lName });
    }
  }
  return deck;
}

console.log(createListOfObjects());

Split the array items to give first and last names and then reutn a new array with each being passed as an object. Note that if an objects key is the same name as a viariable - you don't need to state it.

var namesList = ['Cameron Betts', 'Shana Lopez', 'Angela Li'] ;
createListOfObjects(namesList);

function createListOfObjects(arr) {
  let newArr = [];
  arr.forEach(function(name){
    var namePortions = name.split(' ');
    var firstName = namePortions[0];
    var lastName = namePortions[1];
    newArr.push ({firstName, lastName});
  })
  console.log(newArr);
}

You're not splitting the name string on the space, to separate the first and last names. Also, for every name, you're iterating over every name. meaning that if you were splitting the name right, you would end up with every first name coupled with every last name. What you want is to:

create variable with empty array deckArray.
  iterate over fullNamesArray
  forEach fullNameString
      split the fullNameString on the space character
      to get a tuple (array of two) with [firstName, lastName]
      store firstName and lastName into nameObject
      push nameObject into deckArray
return deckArray

like so

const createListOfObjects = (names) => {
  let deck = [];
  for(let i = 0; i < names.length; i += 1) {
    let [ firstName, LastName ] = names[i].split(' ');
    deck.push({ firstName, lastName });
  }
  return deck;
}
const names = ['Cameron Betts', 'Shana Lopez', 'Angela Li'];
createListOfObjects(names);

better with map

const createListOfObjects = (names) => names.map((fullName) => {
  let [ firstName, lastName ] = fullName.split(' ');
  return { firstName, lastName };
});
发布评论

评论列表(0)

  1. 暂无评论