首页 > 解决方案 > 为新对象创建嵌套对象

问题描述

我试图为新对象创建一个具有完全相同结构(键、值)的新对象。我快到了,但新对象中的嵌套部分有问题。

我停留在需要检查新嵌套对象是否已经分配给它的对象的地方。就像现在一样,我覆盖了嵌套对象部分。我不知道如何解决这部分。我会很感激一些如何解决这个问题的见解。

小提琴: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));

标签: javascriptobjectnested

解决方案


我会建议这样的代码来复制对象

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)

推荐阅读