如果可能,将嵌套JSON结构中的每个对象重命名为其.name属性

时间:2017-02-05 13:53:12

标签: javascript json

我正在寻找一种可以实现以下转型的方式: enter image description here

以下代码包含旧的+新结构:

function test_cleanHierarchyUp() {
  console.log("Test for cleaning up hierarchy")
  // I don't have children, so just keep me as is.
  var bottom_level_object = {
    'test': 'testest',
    'more test': 'test',
    'test': ''
  }

  var middle_object = {
    children: bottom_level_object,
    Name: "Middle Yeah!"
  }

  var original_object = [{
      Name: "I am a name",
      RandomName: '',
      Children: middle_object
    },
    {
      Name: "I am a name too",
      Children: bottom_level_object
    }
  ]

  console.log("-----")
  console.log("Source object: ")
  console.log(original_object)

  // Target structure:
  // I don't have children, so just keep me as is.
  var bottom_level_object_new = {
    'test': 'testest',
    'more test': 'test'
  }

  // Empty string (object 'Random') was removed from object.
  var middle_object_new = {
    "Middle Yeah!": {
      children: bottom_level_object,
      Name: "Middle Yeah!"
    }
  }

  var target_object = {
    "I am a name": {
      Name: "I am a name",
      Children: middle_object_new
    },
    "I am a name too": {
      Name: "I am a name too",
      Children: bottom_level_object_new
    }
  }
  console.log("-----")
  console.log("Target object: ")
  console.log(target_object)

}

我确实尝试过:不幸的是,递归对我来说仍然没有下降。 在代码中有一个小的添加,在相同的递归函数中,我想删除值为空字符串的所有属性。

// Hierarchy Clean up functions
// Todo with this datastructure
//   - How do I remove all fields with value of ""
//   - For each object in the tree, change the object's key into its 'Name' attribute
function cleanHierarchyUp(obj) {
  // obj is an array of objects, with or without a 'children' object (array of objects again)
  // Goal: the object name should be its '.Name' name attribute if it exists
  // Goal: if possible: all 'keys' for which the value is an empty string should be removed.
  obj.forEach(function(element, index) {
    // console.log(element)
    if (element.Children) {
      obj[element.Name] = cleanHierarchyUp(element)
    } else {
      obj[element.Name] = element
    }
  })
  return obj
}

非常感谢帮助或指导。

1 个答案:

答案 0 :(得分:0)

我相信这可以做你想要的:

function createObjectFromArray(objArr) {
    console.log('objArr', objArr);
    var newObject = {};
    objArr.forEach(function(object, index) {
        if (!object.hasOwnProperty('Name') || object.Name.length < 1) return;
        var objectName = object.Name;
        console.log(objectName)
        newObject[objectName] = {};
        newObject[objectName] = setObjectKeys(object, newObject[objectName])
    });
    console.log('newObject', newObject)
    return newObject;
}

function setObjectKeys(object, newObject) {
    Object.keys(object).forEach(function(key){
        if ((typeof object[key] == 'string')) {
            if (object[key].length > 0) {
                newObject[key] = object[key];
            }
        } else if (keyIsObject(object, key)) {
            newObjectKey = key;
            if(object[key].Name) {
                newObjectKey = object[key].Name;
            }
            newObject[newObjectKey] = setObjectKeys(object[key], {});
        } else {
            newObject[key] = object[key];
        }
    });
    return newObject;
}

function keyIsObject(object, key) {
    return Object.prototype.toString.call(object[key]) === '[object Object]';
}

var bottom_level_object = {
    'test': 'testest',
    'more test': 'test',
    'test': ''
}

var middle_object = {
    children: bottom_level_object,
    Name: "Middle Yeah!"
}

var original_object = [{
    Name: "I am a name",
    RandomName: '',
    Children: middle_object
}, {
    Name: "I am a name too",
    Children: bottom_level_object
}];

createObjectFromArray(original_object);