This question already has answers here:
Create an array with same element repeated multiple times
                                
                                    (22个答案)
                                
                        
                                3个月前关闭。
            
                    
我正在尝试创建从对象输入数组获得的多个值的单一数组。理想情况下,我想使用“ ES5”功能来执行此操作。

我需要转换这样的对象:

{
  image: "bat",
  count: 5
}


放入此数组[bat, bat, bat, bat, bat]

我认为代码是解释的最快方法:



//game object state
var gameObj = {
objects: [
  {
    image: "bat",
    count: 5
  },
  {
    image: "spider",
    count: 4
  },
  {
    image: "frankie",
    count: 3
  }
],
imagesArr: [],
}

function gameObjectArrayBuilder(obj) {
  var resultArr = [];
  resultArr = obj.map(buildArr);

  function buildArr(prop) {
    var image = prop.image;
    var count = prop.count;
    while (prop.count > 0) {
      prop.count--
      return prop.image
    }
  }
  return resultArr;

}

gameObj.imagesArr = gameObjectArrayBuilder(gameObj.objects);

//View result
var html = document.querySelector("#content");
html.innerHTML = gameObj.imagesArr;
console.log(gameObj.imagesArr)

//Result should be
//[bat, bat, bat, bat, bat, spider, spider, spider, spider, frankie, frankie, frankie]

<div id="content">

</div>

最佳答案

您可以将new Arrayreduce方法结合使用:



var gameObj = {
  objects: [{
      image: "bat",
      count: 5
    },
    {
      image: "spider",
      count: 4
    },
    {
      image: "frankie",
      count: 3
    }
  ],
  imagesArr: [],
};

function repeatImages(acc, item, idx) {

  if (!(acc instanceof Array)) {
    acc = [];
  }

  return acc.concat(new Array(item.count).fill(item.image));

}

gameObj.imagesArr = gameObj.objects.reduce(repeatImages, []);

console.log(gameObj.imagesArr);

关于javascript - 使用JavaScript从对象映射复合数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58232580/

10-16 18:03