首页 > 解决方案 > 使用包含矢量坐标的另一个对象的对应键更改 2D 数组键名称

问题描述

目标:用每个包含 (x, y) 坐标的表格单元格初始化一个空白棋盘,然后通过用适当的棋子重命名密钥来更新棋盘的相应单元格来填充初始棋子。坐标(键值)将保持不变。

问题:使用 map 函数用适当的棋子更改空白棋盘的键名时遇到问题。

  1) **typeError** from pushing Vector object to an array
  2) **undefined** returned from nested map function

经过研究,更改密钥的一种方法是使用

Object.keys(myObject).map(key => ({[key]: myObject[key]}));

或者

Object.entries(myObject).map(([p, v]) => ({[p]: v}))

但是,当map函数为 2D 数组嵌套时,我无法让它工作。

    const BOARD = `
    wbwbwbwb
    bwbwbwbw
    wbwbwbwb
    bwbwbwbw
    wbwbwbwb
    bwbwbwbw
    wbwbwbwb
    bwbwbwbw
    `;

    const PIECES = `
    rkbqibkr
    pppppppp
    --------
    --------
    --------
    --------
    pppppppp
    rkbqibkr
    `;        

    //class Board    
    static initalize(board, pieces){
    let boardCoords = board.coordinates;
    let pieceCoords = pieces.trim().split("\n").map(l => [...l]);
    let initialPieces = [];
    let startBoard;

    //this is to add the appropriate coordinates of where each chess piece 
    //is at
    //the parameter 'board' that was passed is an instance of the Board 
    //class, where each cell had the appropriate (x, y) coordinates. The 
    //code was exactly the same as below, and it worked. Not sure why it's 
    //not working for below. OUTPUTS: typeError
    this.initialPieces = pieceCoords.map((row, y) => {
        return row.map((ch, x) => {
            if(ch !== '-'){
                this.initialPieces.push(new Vec(x, y)); 
            }
        });
    });

    this.startBoard = Object.entries(boardCoords).map(row, y => {
        key.map(ch, x => {
            if(ch !== "-"){
                ({ [ch]: boardCoords[y][x]});
            }
        });
   });

    return startBoard;
   }}

[试图将向量推入数组]

未捕获的类型错误:无法读取未定义的属性“推送”

[尝试使用 .map(item, item2) 进行映射]

未捕获的 ReferenceError:未定义行

[尝试使用 .map(item) 进行映射]

未捕获的类型错误:无法读取未定义的属性“0”

[预期结果]

[0]: ["p"]: Vec (x, y), ...

标签: javascript

解决方案


推荐阅读