简体   繁体   中英

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:

{
  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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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