从对象数组中的每个对象复制值

时间:2019-10-13 23:21:27

标签: javascript arrays json object

问题:给定一个对象数组,我想通过更改其键名将每个对象复制到一个新数组中。

我正在尝试转换此对象:

  items: [
    {

      "A": "Q1234",
      "B": "W1234",
      "C": 19.9,
      "D": 2
    },
    {
      "A": "Q1234",
      "B": "W1234",
      "C": 19.9,
      "D": 2
    },

对此:

  items: [
    {
      "id": "Q1234",
      "power": "W1234",
      "health": 19.9,
      "mana": 2
    },
    {
      "id": "Q1234",
      "power": "W1234",
      "health": 19.9,
      "mana": 2
    },

我尝试了以下操作,但不起作用:

let replaceAll = () => {
  request.responseText.replace('A','id')
  request.responseText.replace('B','power')
  request.responseText.replace('C','health')
  request.responseText.replace('D','mana')
}

request.responseText输出:

{"id":941282,"items":[{"id":117991,"power":6.5000,"health":102351,"mana":6},{"id":118993,"power":2.5000,"health":103353,"mana":1},{"id":128464,"power":11.6400,"health":112825,"mana":1}]}"

const _myItens = JSON.parse(request.responseText)

2 个答案:

答案 0 :(得分:1)

您可以使用Array.map()destructure对象,并使用aliases用新名称创建变量,然后可以使用shorthand property names重建对象:

const items = [{"A":"Q1234","B":"W1234","C":19.9,"D":2},{"A":"Q1234","B":"W1234","C":19.9,"D":2}]

const result = items.map(({ A: id, B: power, C: health, D: mana }) => ({
  id,
  power,
  health,
  mana
}))

console.log(result)

答案 1 :(得分:0)

输入固定后,您就可以解析JSON,创建一个函数,将对象的ABCD键转换为{ {1}},id等键,以及power该功能上的每个对象:

.map