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

Javascript 如果可能,将嵌套JSON结构中的每个对象重命名为其.name属性,javascript,json,Javascript,Json,我正在寻找一种实现以下转变的方法: 以下代码包含旧+新结构: 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', 't

我正在寻找一种实现以下转变的方法:

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

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
}

非常感谢您的帮助或指导。

我相信这正是您想要的:

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);
函数createObjectFromArray(objArr){
console.log('objArr',objArr);
var newObject={};
forEach(函数(对象、索引){
if(!object.hasOwnProperty('Name')| | object.Name.length<1)返回;
var objectName=object.Name;
console.log(objectName)
newObject[objectName]={};
newObject[objectName]=setObjectKeys(对象,newObject[objectName])
});
console.log('newObject',newObject)
返回newObject;
}
函数setObjectKeys(对象,newObject){
Object.keys(对象).forEach(函数(键){
if((对象的类型[键]='string')){
如果(对象[键]。长度>0){
newObject[key]=对象[key];
}
}else if(键对象(对象,键)){
newObjectKey=key;
if(对象[key].Name){
newObjectKey=对象[key]。名称;
}
newObject[newObjectKey]=setObjectKeys(对象[key],{});
}否则{
newObject[key]=对象[key];
}
});
返回newObject;
}
函数键对象(对象,键){
返回Object.prototype.toString.call(Object[key])=='[Object-Object]';
}
变量底部\级别\对象={
“测试”:“测试人员”,
“更多测试”:“测试”,
“测试”:”
}
var middle_对象={
子对象:底层对象,
名字:“是的!”
}
变量原始对象=[{
名字:“我是一个名字”,
随机名称:“”,
儿童:中间物体
}, {
名字:“我也是一个名字”,
子对象:底层对象
}];
createObjectFromArray(原始对象);

预期结果是object not arrayYeah,我意识到:s“删除值为空字符串的所有属性”是的,已正确修复:)您是从单个小对象开始还是从需要迭代的完整数组开始?提供实际的样本数据而不是数据的图像也将有助于
Middle的转换没有任何意义@charlietfl:原始数据在提供的代码中。因此,基本上,您正在尝试在每一步将数组转换为对象。对吧?这并不能回答问题。这整件事闻起来像是一场灾难。用例是什么?