Javascript 为新对象创建嵌套对象

Javascript 为新对象创建嵌套对象,javascript,object,nested,Javascript,Object,Nested,我正在尝试创建一个与新对象具有完全相同结构(键、值)的新对象。我差一点就到了,但是在新对象中嵌套的部分有问题 我被困在需要检查新嵌套对象是否已指定对象的位置。现在,我将覆盖嵌套对象部分。我不知道如何解决这个问题。我希望能了解如何解决这个问题 小提琴: 我的代码: const interests = [{'name': 'Tennis', 'date': new Date('2019-05-12')}, {'name': 'Golf', 'date': new Date('2019-12-12')

我正在尝试创建一个与新对象具有完全相同结构(键、值)的新对象。我差一点就到了,但是在新对象中嵌套的部分有问题

我被困在需要检查新嵌套对象是否已指定对象的位置。现在,我将覆盖嵌套对象部分。我不知道如何解决这个问题。我希望能了解如何解决这个问题

小提琴:

我的代码:

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)

谢谢,非常好的解决方案!