Adding data to a JSON object in Angular

I am presented with a JSON data structure that contains various keys and values. My goal is to traverse this JSON and extract values for the keys where the 'check' value is set to 'true'.

{
  "A_B":{
    "ID":"09|_|06",
    "address":"ABC",
    "name":"2222222222",
    "Documents":{
      "1":{
        "format":"xlsx"
      },
      "2":{
        "format":"pdf"
      }
    },
    "check":true
  },
  "C_B":{
    "ID":"0a|_|0b",
    "address":"Los Angeles",
    "name":"4444444444",
    "Documents":{
      "1":{
        "format":"docx"
      },
      "4":{
        "format":"xlsx"
      }
    },
    "check":true
  },
  "C_E":{

    "ID":"05|_|06",
    "address":"",
    "name":"1111111111",
    "Documents":{
      "5":{
        "format":"xlsx"
      }
    },
    "check":false
  }
}

Based on the example above, only the values for A_B and C_B should be extracted into a new JSON format. Here is how the new JSON would appear:

{
  "A_B":{
    "ID":"09|_|06",
    "address":"ABC",
    "name":"2222222222",
    "Documents":{
      "1":{
        "format":"xlsx"
      },
      "2":{
        "format":"pdf"
      }
    },
    "check":true
  },
  "C_B":{
    "ID":"0a|_|0b",
    "address":"Los Angeles",
    "name":"4444444444",
    "Documents":{
      "1":{
        "format":"docx"
      },
      "4":{
        "format":"xlsx"
      }
    },
    "check":true
  }
}

I have been successful in identifying the IDs [A_B and C_B] where 'check' === true using the following code:

var IDs = Object.keys(completeJson);
var checkTrueIDs = IDs.reduce(function(initArr,ID) {
        if(completeJson.check === true) {
                initArr.push(ID);
        }
        return initArr;
},[]);
console.log("IDs wth check === true - " + checkTrueIDs);

However, I am struggling to retrieve the complete object for these identified IDs and incorporate them into a new JSON. When attempting to do so by creating a new JSON object and assigning values inside the conditional statement after the push operation:

var newJson = {}
newJson = completeJson[ID];

The previous values get overwritten, resulting in only retaining one object in the end.

Answer №1

To filter out the items that have a specific key set to true, you can loop through the object and add those items to a new JSON object.

var filteredJson = {};
    angular.forEach(originalJson, function(val, k) {
        if(val.key){
            filteredJson[k] = val;
        }
    });
console.log(filteredJson);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to convert this from a string to HTML format?

I recently encountered an issue where my code was being converted into a string instead of the HTML output I intended to achieve. My main query is how can I convert this into innerHTML before it gets converted? Is there any way to accomplish this task if ...

Can state values be utilized as content for Meta tags?

I am looking for a way to display image previews and titles when sharing a page link. In order to achieve this, I am using the Nextjs Head Component. The necessary details are fetched on page load and used as content for the meta attributes. let campaign = ...

Utilize the onChangeText function in React Native to filter out each individual value within a nested array

I currently have an array with nested children in it, where the children can range from one to multiple values. I am working on implementing a local filter within my component. Whenever a user types anything into the textInput, the application will display ...

Sending the `<path>` wrapped in quotes to `<SvgIcon>` is resulting in the SVG not rendering

When I try to use the Material-UI's SvgIcon component, the <path> element is surrounded by quotes, which is preventing the SVG from rendering properly. https://i.stack.imgur.com/InDRt.png I'm currently working in Storybook within an MDX f ...

In right-to-left mode, two items in Owl Carousel vanish while dragging or touching

When using owl carousel 2 with the RTL option, I encountered an issue where the carousel disappears when dragging/touching the last item (5 or 6 slides to the right, it disappears). I prefer not to use the loop option to workaround this. How can I resolve ...

Issue with mediaelement in Angular 8: video playback does not display after 2 seconds

I'm encountering an issue with MediaElement js when trying to play videos in .m3u8 format within a slider containing multiple videos. Whenever I click on the play button for any video, only a 2-second clip is shown before the video disappears. Any as ...

What is the method to make a file download using JavaScript?

In my jQuery ajax form, a user inputs their email and upon submission, they should receive an automatic download of a file. Here is the structure of the form: $(".email-form").submit(function(event) { event.preventDefault(); var $form = $(this), ...

activate the button once valid input has been provided

How can I enable a button based on the amount entered? Let's say there is a minimum of 100 and a maximum of 200. If the user enters an amount below 100, display an error message and keep the button disabled. If the user enters an amount above 200, ...

Oops! An unexpected error occurred: TypeError - Seems like _this.searchElementRef is not defined

I recently implemented the Google Place API in my project by following this tutorial. However, I encountered the following error: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined The issue seems ...

Problem with Sending POST Requests in ExpressJS

Having trouble with a POST request in Postman resulting in a long loading time followed by a Could not get any response error message? No errors are showing up in the terminal. Could there be an issue with how I am saving the POST data, especially in my /b ...

In what scenario should I respond with true or false to AJAX, and when is it more appropriate to use the echo function to output "true" or "false

It seems I have managed to confuse myself. I mistakenly believed that when using AJAX to communicate with PHP (like $.post), one had to echo back a "true" or "false" instead of simply returning true or false. I now realize this is not the case, but could ...

Calculating the mean value of the numbers provided in the input

I'm struggling with calculating the average of numbers entered through a prompt window. I want to display the numbers as I've done so far, but combining them to find the average is proving difficult. Here's the code I have: <html> &l ...

Testing Angular Components Using HostListener

I am looking to write unit tests for @HostListener, but I'm unsure of how to go about it since it's located on top of the component. Here is an example of the code: @HostListener('document:click', ['$event']) onDocumentClick ...

Submitting form via ajax whenever triggered

I am looking for a way to submit each form individually by clicking on the submit button. My question: How can I send each form separately and display the results accordingly? The code I have tried does not seem to be working, as nothing is being sent and ...

Learn how to efficiently handle asynchronous tasks while also defining permissions with the Angular permission library

Currently, I am utilizing the angular-permission library in conjunction with ui-router and satellizer. The state definition for home is as follows. I am verifying the user's authorization status using angular-permission. $stateProvider.state('5 ...

A step-by-step guide to extracting a JSON object from an HTTP request using Java

Currently, I am attempting to retrieve a JSON Object using an HTTP request in Java code. I am seeking guidance on how to obtain the response or JSON object within the following code. Your help is much appreciated. (I am attempting to fetch Wikipedia cat ...

Sending two variables as JSON in Django using HTML can be achieved by creating a JSON object in the JavaScript

I need to display two different HTML samples and return them as a response to an AJAX request. Here is a snippet of my code in the view: def getClasses(request): User = request.user aircomcode = request.POST.get('aircompany_choice', Fals ...

Utilizing jQuery to select an attribute containing a special character

There is a special div with a unique data-id: <div data-id=""> </div> I tried to target this div using jQuery, but it didn't work as expected: jQuery("[data-id='']").text('hello'); Can anyone help me on how to ...

Using Javascript to swap out elements sharing the same classname with distinct contents

Just a quick question: Can you replace the values of elements with the SAME class with different values? For example, let's say I have this array returned by an AJAX response: [ "$63.00 / Night", "$68.00 / Night", "$58.00 / Night", "$50.00 / ...

In React, components will consistently render the initial code

I have a chat application that requires authentication and uses cookies. Here's what I've been attempting: class AppHeader extends React.Component { constructor(props) { super(props) } render() { if (cookies.get(' ...