Search code examples
javascriptarraysangularjsjsonlodash

How to omit a particular key while pushing json objects to an array?


So, I have a JSON array of objects , which in turn contains other arrays of objects. This array of objects has no particular fixed structure as such so its very difficult for me do something like delete mainArray[0].obj.subobj[1].objToOmit;

So I have a key/object called possibleAnswers which I need to remove/omit. In my program I am pushing the contents of one array into another array. So while I am pushing the contents of first array of objects into another, I need to omit the possibleAnswers object from being pushed.

Is there any way or function that searches an array of objects and helps me omit the necessary key? Or what would be a solution as per your thoughts?

Example :

Here is a minimal example: https://codebeautify.org/jsonviewer/cb9fea0d Edit: In the above JSON there is a key called possibleMembers which is wrong. its possibleAnswers

            var collectObservationsFromConceptSets = function () {
            $scope.consultation.observations = [];
            _.each($scope.consultation.selectedObsTemplates, function (conceptSetSection) {
                if (conceptSetSection.observations) {
                    _.each(conceptSetSection.observations, function (obs) {
                        $scope.consultation.observations.push(obs);
                    });
                }
            });
        }

In the above code while pushing the object into another array, how can I omit the possibleAnswers keys? Is there a way to omit?

Thanks a lot people! Both the answers are correct and have generated the exact correct output. Unfortunately I can only select 1 answer as correct and its going to be random.


Solution

  • This is a recursive omit that uses _.transform() to iterate and ignore one or more keys in an array:

    const omitRecursive = (keys, obj) => _.transform(obj, (acc, v, k) => {
      // if key is view, and it and has an id value replace it with equivalent from views
      if(keys.includes(k)) return;
      
      acc[k] = _.isObject(v) ? omitRecursive(keys, v) : v;
    });
    
    const data = [{"observations":[{"possibleAnswers":[],"groupMembers":[{"possibleAnswers":[]},{"groupMembers":[{"possibleMembers":[]},{"possibleMembers":[]}]}]}]},{"observations":"Same as above"},{"observations":"Same as above"}];
    
    const result = omitRecursive(['possibleAnswers'], data);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>