如何更改对象数组中的属性

时间:2018-03-10 10:18:08

标签: javascript arrays

我有一个包含800个对象的数组。

cells = [
    { x_position: 0, y_position: 0, terrain: 'water' },
    { x_position: 0, y_position: 1, terrain: 'water' },
    { x_position: 0, y_position: 2, terrain: 'water' },
    { x_position: 0, y_position: 3, terrain: 'water' },
    { x_position: 0, y_position: 4, terrain: 'water' },
    ...
]

让我们说一些x_positiony_position我想将terrain更改为'land'

如何迭代更改地形的数组?

5 个答案:

答案 0 :(得分:2)

您可以使用forEach()

let cells = [
    { x_position: 0, y_position: 0, terrain: 'water' },
    { x_position: 0, y_position: 1, terrain: 'water' },
    { x_position: 0, y_position: 2, terrain: 'water' },
    { x_position: 0, y_position: 3, terrain: 'water' },
    { x_position: 0, y_position: 4, terrain: 'water' }
];

let match = {
  x_position: 0,
  y_position: 2
}

cells.forEach(o => {
  if(o.x_position == match.x_position && o.y_position == match.y_position)
    o.terrain = 'land';
});

console.log(cells);

答案 1 :(得分:1)

您可以使用Array.prototype.map迭代数组并更改对象的terrain值;

注意我的解决方案是不可变的,这意味着它不会改变原始数组和对象。

const cells = [{
    x_position: 0,
    y_position: 0,
    terrain: 'water'
  },
  {
    x_position: 1,
    y_position: 1,
    terrain: 'water'
  },
  {
    x_position: 0,
    y_position: 2,
    terrain: 'water'
  },
  {
    x_position: 0,
    y_position: 3,
    terrain: 'water'
  },
  {
    x_position: 0,
    y_position: 4,
    terrain: 'water'
  }
];

const result = cells.map((item) => {
  if (item.x_position === 1) {
    return { ...item,
      terrain: 'land'
    }
  } else {
    return item;
  }
});

console.log(result)

答案 2 :(得分:1)

只需使用此代码。

 var cells = [
        { x_position: 0, y_position: 0, terrain: 'water' },
        { x_position: 0, y_position: 1, terrain: 'water' },
        { x_position: 0, y_position: 2, terrain: 'water' },
        { x_position: 0, y_position: 3, terrain: 'water' },
        { x_position: 0, y_position: 4, terrain: 'water' },
      ];
       var i;
       for (i = 0; i < cells.length; i++) {
          cells[i].land = cells[i]['terrain'];
          delete cells[i].terrain;
       } console.log(cells);

答案 3 :(得分:0)

从长远来看,建立一个位置散列图可能会很好:

 const byPosition = {};

 for(const cell of cells)
   byPosition[cell.position_x + "|" + cell.position_y] = cell;

所以你可以这样做:

byPosition["1|2"].terrain = "landscape";

如果你的细胞以某种方式形成一个正方形,你应该绝对使用一个二维数组来存储它们。

答案 4 :(得分:0)

您可以使用array.prototype.find找到该元素,然后将terain属性的值更改为Land:

var cells = [
    { x_position: 0, y_position: 0, terrain: 'water' },
    { x_position: 0, y_position: 1, terrain: 'water' },
    { x_position: 0, y_position: 2, terrain: 'water' },
    { x_position: 0, y_position: 3, terrain: 'water' },
    { x_position: 0, y_position: 4, terrain: 'water' }
];
var x = 0, y = 2;
var item = cells.find(c => c.x_position === x && c.y_position === y);
item && item.terrain = 'land';