How to map a object of objects getting the key and value?

Viewed 585

I have map called "marks" that has other maps as fields. I need to do something like a forEach loop (or a map) with this getting the key and the value of each nested map.

This is my data:

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

What I am trying to do is:

 // 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
 })

Any ideas? The resulted data has to look like this:

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

Below snippet could help you

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)

Ref:

  • Object.keys() doc
  • Object.entries() doc

Could use a for...in loop:

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)


Though, you should note:

The problem with a for...in loop is that it iterates through properties in the Prototype chain. When you loop through an object with the for...in loop, you need to check if the property belongs to the object. You can do this with hasOwnProperty.

So to account for this:

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)


This is a good article to check out for something like this.

if you have undetermined number of properties inside your object you can do nested for like that

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);
Related