javascript - 为新对象创建嵌套对象
问题描述
我试图为新对象创建一个具有完全相同结构(键、值)的新对象。我快到了,但新对象中的嵌套部分有问题。
我停留在需要检查新嵌套对象是否已经分配给它的对象的地方。就像现在一样,我覆盖了嵌套对象部分。我不知道如何解决这部分。我会很感激一些如何解决这个问题的见解。
小提琴:https ://jsfiddle.net/u758px3h/
我的代码:
const interests = [{'name': 'Tennis', 'date': new Date('2019-05-12')}, {'name': 'Golf', 'date': new Date('2019-12-12')}];
const person = {'id': 82, 'name': 'John', 'interests': interests};
let newObject = {};
function test(object, key) {
Object.keys(object).map((objectKey) => {
if (typeof(object[objectKey]) === 'object' && !(object[objectKey] instanceof Date)) {
Object.keys(object[objectKey]).map((innerKey) => {
test(object[objectKey][innerKey], objectKey);
});
} else {
if (key !== undefined) {
if (newObject[key] === undefined) {
newObject[key] = [];
}
newObject[key][objectKey] = object[objectKey];
} else {
newObject[objectKey] = object[objectKey];
}
}
});
return newObject;
}
console.log(test(person));
解决方案
我会建议这样的代码来复制对象
const interests = [{'name': 'Tennis', 'date': new Date('2019-05-12')}, {'name': 'Golf', 'date': new Date('2019-12-12')}];
const person = {'id': 82, 'name': 'John', 'interests': interests};
function copyObject(object, objectsMap = []) {
// lets copy object
const newObject = Array.isArray(object) ? [...object] : { ...object}
// iterate each property to check if it is object or not
for (let key in newObject) {
const value = newObject[key]
if (typeof value === 'object' && value !== null && !(value instanceof Date)) {
let newValue
// check in objectsMap was the same object copied before
const createdObject = objectsMap.find(v => v.oldObject === value)
if (createdObject) { // if yes then just assign created before object
newValue = createdObject.newObject
} else { // if no then copy this object and add to objectsMap
newValue = copyObject(value, objectsMap)
objectsMap.push({ oldObject: value, newObject: newValue})
}
// assign newValue to current key
newObject[key] = newValue
}
}
return newObject
}
const newInterests = copyObject(interests)
console.log(newInterests)
推荐阅读
- python - 使用两个单独的变量存储嵌套 for 循环中的值
- r - pROC:ROC 曲线上未正确显示灵敏度下限
- python - List comprehension with multiple if-conditions
- spring - spring hatoas 1.1.0 基本 rel 路径被截断
- python - 跳过未找到的字符串 Python
- javascript - 将存储在数组中的日期值更改为两周前
- node.js - Angular CLI [npm install -g @angular/cli] 出现错误 SyntaxError: Unexpected token } in JSON at position
- java - 由于 java.util.concurrent.TimeoutException,Eclipse 2020-06 不断冻结
- git - Git,删除我现在不需要推送的本地提交
- django - 在身份验证类中的 Django REST 框架中向请求添加数据