使用Java Script

时间:2015-10-27 06:43:52

标签: javascript json

我们正在寻找一个示例代码,使用Java Script删除JSON消息中的嵌套元素。此元素名称将从其他函数动态获取。

删除路径:

privateNetwork.floor.block.network.name

我们确信以下内容适用于硬编码:

delete jsonobj[privateNetwork][floor][block][network][name]

但是如何在动态场景中实现这一目标 例如:在第二次尝试中我们需要删除privateNetwork.floor.room

1 个答案:

答案 0 :(得分:0)

将您的属性名称拆分为一个数组,循环遍历它,直到找到它的直接父项(在最后一项旁边)并使用它来删除最里面的字段(数组的最后一项)

var deepObject = {
  privateNetwork: {
    floor: {
      room: 'Room 1408'
    }
  }
}

// Find object property recursively by string path
var deepFind = function (obj, path) {
  var current=obj; 
  path.split('.').forEach(function(p){ current = current[p]; }); 
  return current;
}

var dynamicPropertyName = 'privateNetwork.floor.room';

var innermostObjectName = dynamicPropertyName.substring(0, dynamicPropertyName.lastIndexOf('.'));
var fieldName = dynamicPropertyName.substring(dynamicPropertyName.lastIndexOf('.') + 1);

var innermostObject = deepFind(deepObject, innermostObjectName);
delete innermostObject[fieldName];

console.log(deepObject);

https://jsfiddle.net/7r6avpsy/