[英]update nested value in object of objects with keys in javascript
I have a nested object:我有一个嵌套的 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:我想将每个嵌套的 object 中的created_at
和updated_at
转换为仅返回seconds
,而不是像这样的数字:
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?我在想我需要混合使用map
和Object.assign
以及传播运算符?
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?这样做的正确方法是什么?
Use forEach()
to iterate over the values and then just reassign the properties.使用forEach()
迭代值,然后重新分配属性。
Object.values(myObject).forEach(item => {
item.created_at = item.created_at.seconds;
item.updated_at = item.updated_at.seconds;
});
Using Object#fromEntries
, Object#entries
, and Array#map
:使用Object#fromEntries
、 Object#entries
和Array#map
:
const 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 } } }; const res = Object.fromEntries( Object.entries(myObject).map(([ key, value ]) => ([ key, {...value, 'created_at': value['created_at'].seconds, 'updated_at': value['updated_at'].seconds, } ])) ); console.log(res);
for (let key in obj) { obj[key].created_at = obj[key].created_at.seconds; obj[key].updated_at = obj[key].updated_at.seconds; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.