[英]How to remove all nested arrays and objects from javascript object
I have an angularjs scope object with various nested objects and arrays like so: 我有一个带有各种嵌套对象和数组的angularjs作用域对象,如下所示:
{
prop1: 'prop1'
prop2: 'prop2'
prop3: 'prop3'
nestedArray1:
0:
prop1: 'prop1'
prop2: 'prop2'
1:
prop1: 'prop1'
prop2: 'prop2'
nestedObj1:
prop1: 'prop1'
prop2: 'prop2'
nestedObj2:
prop1: 'prop1'
prop2: 'prop2'
....
}
I need to save the top level object via an api, and am currently using the following coffeescript function to manually delete the nested objects and arrays before sending it to the server: 我需要通过api保存顶级对象,当前正在使用以下coffeescript函数在将嵌套对象和数组发送到服务器之前手动删除它们:
$scope.save = ->
params = angular.copy($scope.mainObj)
delete params.nestedArray1
delete params.nestedObj2
delete params.nestedObj3
$api.update(obj: params).$promise.then ((response) ->
Flash.create('success', 'Changes saved.')
), (error) ->
Flash.create('danger', 'There\'s been a problem with our servers. Please try again later.')
How can I refactor the function to recursively remove all nested objects and arrays, so I can reuse it elsewhere? 如何重构该函数以递归方式删除所有嵌套对象和数组,以便可以在其他地方重用它?
You can write a function to just make a copy of the top-level properties that are themselves not objects: 您可以编写一个函数以仅复制本身不是对象的顶级属性:
function copyTop(obj) {
var o = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] !== "object") {
o[prop] = obj[prop];
}
}
return o;
}
This will return you a new object that just has the top level properties in it that were not themselves nested objects. 这将为您返回一个新对象,该对象仅具有顶层属性,而这些属性本身并不是嵌套对象。 You shouldn't have to do this recursively unless you also want top level properties of nested objects too that are not themselves objects, but in that case, you'd have to specify what to do when there are properties at different levels with the same property name. 除非您还希望嵌套对象的顶级属性本身不是对象,否则不必递归执行此操作,但是在这种情况下,当不同级别的属性具有相同的属性时,您必须指定要做什么属性名称。
Working snippet demo: 工作片段演示:
var data = { prop1: 'p1', prop2: 'p2', prop3: 'p3', nestedArray1: [ { prop1: 'prop1', prop2: 'prop2'}, { prop1: 'prop1', prop2: 'prop2'} ], nestedObj1: { prop1: 'prop1', prop2: 'prop2' }, nestedObj2: { prop1: 'prop1', prop2: 'prop2' } } function copyTop(obj) { var o = {}; for (var prop in obj) { if (obj.hasOwnProperty(prop) && typeof obj[prop] !== "object") { o[prop] = obj[prop]; } } return o; } var result = copyTop(data); document.write(JSON.stringify(result));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.