返回一个对象数组

时间:2016-12-29 15:11:14

标签: javascript arrays object

我有这个功能:

buildDeck = () => {
    let suit = ['C', 'D', 'H', 'S'];
    let rank = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
    let deck = [];
    for (var i=0; i < rank.length; i++){
      for (var k=0; k < suit.length; k++){
        deck.push(rank[i] + suit[k])
      }
    };
    return deck;
  }

这会返回一个像['2C', '4D', etc]这样的数组 我希望它能返回一个对象数组,所以每个对象内部都是: 西装:'C',等级:4例如 如何将一个字符串数组转换为一个对象数组,其中rank和suit是每个对象中的属性?

3 个答案:

答案 0 :(得分:2)

试试这个

buildDeck = () => {
    let suit = ['C', 'D', 'H', 'S'];
    let rank = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
    let deck = [];
    for (var i=0; i < rank.length; i++){
      for (var k=0; k < suit.length; k++){
        deck.push({ rank: rank[i], suit: suit[k]})
      }
    };
    return deck;
}

答案 1 :(得分:0)

您可以使用箭头功能以及排名和套装。

var buildDeck = deck =>
        [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].forEach(rank =>
            ['C', 'D', 'H', 'S'].forEach(suit =>
                deck.push({rank, suit}))),
    deck = [];

buildDeck(deck)
console.log(deck);
.as-console-wrapper { max-height: 100% !important; top: 0; }

或使用发电机

function* buildDeck() {
    for (let rank of [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) {
        for (let suit of ['C', 'D', 'H', 'S']) {
            yield {rank, suit};
        };
    };
}

var deck = [...buildDeck()];
console.log(deck);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

在套装和等级上运行两个嵌套地图,构建一个小套装/等级对象的嵌套数组,然后用concat(...展平。

const buildDeck = () => {
  let suits = ['C', 'D', 'H', 'S'];
  let ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];

  return [].concat(...suits.map(suit => ranks.map(rank =>({suit, rank}))));
}

console.log(buildDeck());