如何映射一个包含键值对的对象的对象?

4

我有一个名为 "marks" 的地图,其具有其他地图作为字段。 我需要类似于使用forEach循环(或map)的方式来获取每个嵌套地图的键和值。

这是我的数据:

   "marks" : {
       "mark_01": {x: 10, y: 200},
       "mark_02": {x: 200, y: 100},
        ...
       "mark_99": {x: 1000, y: 1039}
    }

我想做的是:

 // This is wrong but represents the main idea
 const newMarks = marks.map(mark => {
    // Get the mark key "mark_number"
    // Change its value (x, y)
    // Return an object with the same key and the new manipulated value
 })

有任何想法吗?生成的数据必须如下所示:

"marks" : {
      "mark_01" : {x: 0, y: 190},
      "mark_02" : {x: 190, y: 90},
       ...
      "mark_99" : {x: 990, y: 1029}
 }
4个回答

4
以下片段可以帮助您:

const { marks } = {
  marks: {
    mark_01: { x: 10, y: 200, other_if_have: 'a' },
    mark_02: { x: 200, y: 100, other_if_have: 'b' },
    mark_99: { x: 1000, y: 1039, other_if_have: 'c' },
  },
}

const temp = Object.keys(marks).map((mark) => {
  const manipulate = ({ x, y }) => ({
    x: x - 10,
    y: y - 10,
  })
  return [mark, { ...marks[mark], ...manipulate(marks[mark]) }]
})

const res = { marks: Object.fromEntries(temp) }

console.log(res)

参考文献:


2

1
可以使用 for...in 循环:

const marks = {
  "mark_01": {
    x: 10,
    y: 200
  },
  "mark_02": {
    x: 200,
    y: 100
  },
  "mark_99": {
    x: 1000,
    y: 1039
  }
}

console.log("before", marks)

for (let i in marks) {
  marks[i].x += 1;
  marks[i].y += 1;
}

console.log("after", marks)


但是需要注意:

使用 for...in 循环的问题在于它会遍历原型链上的属性。当你用 for...in 循环遍历对象时,需要检查属性是否属于该对象。可以使用 hasOwnProperty 方法进行检查。

因此,为了解决这个问题:

const marks = {
  "mark_01": {
    x: 10,
    y: 200
  },
  "mark_02": {
    x: 200,
    y: 100
  },
  "mark_99": {
    x: 1000,
    y: 1039
  }
}

console.log("before", marks)

for (let i in marks) {
  if (marks.hasOwnProperty(i)) {
    marks[i].x += 1;
    marks[i].y += 1;
  }
}

console.log("after", marks)


这篇文章 是一个检查类似内容的好文章。


1
如果您的对象中有数量未确定的属性,您可以像这样进行嵌套循环。
let marks = {
  "mark_01": {x: 10, y: 200, z: 300, ...},
  "mark_02": {x: 200, y: 100, z: 10, ...},
  "mark_99": {x: 1000, y: 1039, z: 1200, ...}
}

let newMarks = {}
for (const [key, value] of Object.entries(marks)) {
  let newValues = {}
  for (const [innerKey, innerValue] of Object.entries(value)) {
    newValues[innerKey] = innerValue - 10
  }
  newMarks[key] = newValues
}
console.log(newMarks);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接