Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

update nested value in object of objects with keys in javascript

I have a nested object:

myObject {
  "fshkj78gds": {
    "name": "Joe",
    "created_at": {
      "nanoseconds": 745000000,
      "seconds": 1645468219,
    },
    "updated_at": {
      "nanoseconds": 0,
      "seconds": 1645471800,
    },
  },
  "gsdg987": {
    "name": "Mike",
    "created_at": {
      "nanoseconds": 745000000,
      "seconds": 1645468219,
    },
    "updated_at": {
      "nanoseconds": 0,
      "seconds": 1645471800,
    },
  },
}

I would like to convert created_at and updated_at in each nested object to only return the seconds instead as a number like so:

myObject {
  "fshkj78gds": {
    "name": "Joe",
    "created_at": 1645468219,
    "updated_at": 1645471800,
  },
  "gsdg987": {
    "name": "Joe",
    "created_at": 1645468219,
    "updated_at": 1645471800,
  },
}

I am thinking I will need a mix of map and Object.assign as well as spread operator?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So far I got to:

Object.assign({}, myObject, Object.values(myObject).map((nestedObject) =>
  Object.assign({}, nestedObject, {...nestedObject, created_at: nestedObject.created_at.seconds})
))

But this generates an array of objects and doesn’t keep the original structure. What’s the proper way to do this?

>Solution :

Use forEach() to iterate over the values and then just reassign the properties.

Object.values(myObject).forEach(item => {
    item.created_at = item.created_at.seconds;
    item.updated_at = item.updated_at.seconds;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading