简体   繁体   English

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

[英]Rename each object in a nested JSON structure to its .name property if possible

I'm looking for a way in which I can achieve the following transformation: 我正在寻找一种可以实现以下转换的方法: 在此处输入图片说明

The following code contains the old + new structure: 以下代码包含新旧结构:

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)

}

I did try: Recursion still hasn't dropped for me, unfortunately. 我确实尝试过:不幸的是,递归对我而言仍然没有放弃。 A minor addition is in the code, in the same recursion function I'd like to remove all attributes for which the value is an empty string. 在代码中,在相同的递归函数中做了一个小小的添加,我想删除所有值为空字符串的属性。

// 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
}

Help or direction is greatly appreciated. 帮助或指示,不胜感激。

I believe this does what you want: 我相信这可以满足您的需求:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM