Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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}
 }
like image 475
Victor Molina Avatar asked Jan 25 '23 19:01

Victor Molina


1 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
like image 145
hgb123 Avatar answered Jan 27 '23 10:01

hgb123