如何将数组作为对象数组返回?

时间:2018-11-23 00:42:50

标签: javascript arrays object javascript-objects

我进行以下锻炼:

  • 编写一个名为createListOfObjects的函数,该函数接受一个
  • 包含名字和姓氏并返回的字符串数组
  • 一组对象,每个对象具有属性firstName
  • lastName以及名字和姓氏值
  • 对应值 *
  • var namesList = ['Cameron Betts','Shana Lopez','Angela Li'] *
  • createListOfObjects(namesList)
  • =>
  • [
  • {firstName:“ Camer”,lastName:“ Betts”},
  • {firstName:“ Shana”,lastName:“ Lopez”},
  • {firstName:“ Angela”,lastName:“ Li”}
  • ]

直到现在我的解决方案:

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());

但是它返回以下内容:

enter image description here

我必须从数组中提取名称,然后将其拆分以用于我的for,但我不知道我该怎么做。

3 个答案:

答案 0 :(得分:3)

一个选项是split每个全名,以便具有名字和姓氏,然后可以从这两个变量中创建一个对象。理想情况下,为此使用.map-.map是将一个数组中的每个元素转换为另一个数组的最合适方法:

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

要修复您现有的代码,您仅需要<{>一次(无嵌套循环)就迭代names,并且在每次迭代中,split重复名称字符串,并推送到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());

答案 1 :(得分:1)

拆分数组项以提供名字和姓氏,然后重新创建一个新数组,并将每个数组作为对象传递。请注意,如果对象键的名称与Viariable相同,则无需声明它。

#[derive(Debug)]
struct Bar;

struct Foo<'a> {
    bar: &'a Bar
}

impl<'a> Foo<'a> {
    pub fn get_bar_ref(& self) -> &'a Bar {
        self.bar
    }
}

fn main() {
    let bar_ref;
    {                                   
        let foo=Foo{bar:&Bar{}};        //(1) anonymous Bar is created here 
        bar_ref=foo.get_bar_ref();
    }                                   //(2) its lifetime should be ended here
    println!("{:?}",bar_ref);           //(3) but the reference is still valid here
}

答案 2 :(得分:0)

您不会在空格上拆分名称字符串,以分隔名字和姓氏。 另外,对于每个名称,您都要遍历每个名​​称。 意思是,如果您将名称拆分为正确的名称,那么您将以每个名字和每个姓氏结尾。 您想要的是:

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

像这样

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

更好的地图

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