返回包含从数组中选择的对象信息的对象数组

时间:2019-01-14 09:32:33

标签: javascript arrays object

            /**
          * A prototype to create Animal objects
          */
        function Animal (name, type, breed) {
            this.name = name;
             this.type = type;
             this.breed = breed;
        }

         function createAnimalObjects(names, types, breeds) {
            // IMPLEMENT THIS FUNCTION!
            }
    /* Input should be like this

    a_name = ['Dog','Cat', 'Fowl','Goat'];
    a_type = ['Security Dog', 'Blue Eyes', 'Cock', 'she Goat'];
    a_breed = ['German Shepherd', 'Noiseless', 'African Cock', 'American Goat'];
    createAnimalObjects(a_name,a_type,a_breed);
    */
    /* *
    [Animal{name:'Dog', type:'Security Dog' ,breed:'German Shepherd'},
Animal{name:'Cat', type:'Blue Eyes', breed:'Noiseless'}
......etc]

使用上述原型,数组应返回新的动物对象。请帮助注释您的代码以使其清晰。是学习者。

2 个答案:

答案 0 :(得分:0)

这是一个简单的map操作

function Animal (name, type, breed) {
    this.name = name;
    this.type = type;
    this.breed = breed;
}

function createAnimalObjects(names, types, breeds) {
    if ([...arguments].some(({length}) => length !== names.length)) throw new Error('length doesnt match');
    return names.map((e, i) => new Animal(e, types[i], breeds[i]));
}

a_name = ['Dog','Cat', 'Fowl','Goat'];
a_type = ['Security Dog', 'Blue Eyes', 'Cock', 'she Goat'];
a_breed = ['German Shepherd', 'Noiseless', 'African Cock', 'American Goat'];

console.log(createAnimalObjects(a_name, a_type, a_breed));

答案 1 :(得分:0)

当您要组合多个数组时,通常是通过zip函数完成的:

const zip = (...arrays) =>
  [
    ...new Array(
      Math.max(...arrays.map((array) => array.length)),
    ).keys(),
  ].map((index) =>
    arrays.reduce(
      (result, array) => result.concat(array[index]),
      [],
    ),
  );

console.log(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]));

现在您可以使用zip组合数组,然后将其映射到Animal值数组

const zip = (...arrays) =>
  [
    ...new Array(//.keys returns iterator, spread this to new array
      Math.max(...arrays.map((array) => array.length)),//longest array
    ).keys(),
  ].map((index) =>
    arrays.reduce(
      (result, array) => result.concat(array[index]),
      [],
    ),
  );

const a_name = ['Dog', 'Cat', 'Fowl', 'Goat'];
const a_type = ['Security Dog','Blue Eyes','Cock','she Goat'];
const a_breed = ['German Shepherd','Noiseless','African Cock','American Goat'];

function Animal(name, type, breed) {
  this.name = name;
  this.type = type;
  this.breed = breed;
}

console.log(
  //zip returns [[names[0],types[0],breeds[0]],[names[1],types[1],breeds[1],...]
  zip(a_name, a_type, a_breed) 
    .map(
      ([name, type, breed]) =>//destructure [name,type,breed]
        new Animal(name, type, breed),
    ),
);

某些文档:destructure syntaxspreadArray.prototype.mapArray.prototype.reduce