创建嵌套对象到新对象

时间:2019-10-06 19:41:33

标签: javascript object nested

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

我被困在需要检查新嵌套对象是否已经分配了对象的位置。现在,我覆盖了嵌套对象部分。我不确定如何解决这一部分。我将对如何解决此问题有一些见解。

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

1 个答案:

答案 0 :(得分:0)

我建议使用此类代码复制对象

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)