[英]How to map a object of objects getting the key and value?
我有 map 稱為“標記”,其中有其他地圖作為字段。 我需要執行類似 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}
}
下面的片段可以幫助你
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)
參考:
另一種替代解決方案:
const edited = Object.fromEntries(Object.entries(marks).map(
([k,{x,y}]) => [k,{x: x+10, y: y+10}]
));
你可以在這里查看: https://jsfiddle.net/sandro_paganotti/ztw1exb4/13/
可以使用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 循環的問題在於它遍歷 Prototype 鏈中的屬性。 當您使用 for...in 循環遍歷 object 時,您需要檢查該屬性是否屬於 object。 您可以使用 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)
這是一篇很好的文章,可以查看類似的內容。
如果您的 object 中有未確定數量的屬性,您可以這樣做嵌套
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.