Angular.js provides a solution for parsing a unique structure of JSON array containing objects

How can an angular for each loop be used to handle the json array of objects provided in the formatted data below? The key represents the id and the value represents the title. Any suggestions on how to accomplish this task? Thank you.

mycode

me.record.questionaires = []
angular.forEach(detail.questionaires, function (value, key) {
            me.record.questionaires.push({ "id": key, "title": value })

        });

Formatted JSON Data (detail.questionaire result)

[  
   "{'sub_title': 'dsadsa', 'instruction': 'You Must',…elimit': '01:05:19', 'title': 'asdsa', 'id': 133}",
   "{'sub_title': 'sdasdsa', 'instruction': None, 'cre…melimit': '05:30:09', 'title': 'asda', 'id': 131}"
]

Answer №1

To get the desired result, follow these steps:

  1. Iterate through the array
  2. Convert the string into JSON format
  3. Add or transform the necessary data values into your questionaires array (clarify the type of data needed)
me.record.questionaires = detail.questionaires.map(json => {
  let { id, title } = JSON.parse(json)
  return { id, title }
})

Answer №2

I made some modifications to the JSON code you provided as it was causing errors in the console. Take a look and see if this resolves the issue.

angular
  .module("myModule", [])
  .controller("myController", function($scope) {
    var me ={record: {questionaires: []}};
    $scope.me = me;

    var detail ={};
    detail.questionaires = [  
      "{'sub_title': 'dsadsa', 'instruction': 'You Must','…elimit': '01:05:19', 'title': 'asdsa', id: 133}",
      '{"sub_title": "sdasdsa", "instruction": "None", "cre…melimit": "05:30:09", "title": "asda", "id": 131}'
    ];

    angular.forEach(detail.questionaires, function (value, key) {
    
      var questionaire = JSON.parse(value.replace(/'/g, '"').replace(/id:/g, '"id":'));     
      me.record.questionaires.push({ "id": questionaire.id, "title": questionaire.title });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="myModule">
  <div ng-controller="myController">
  <div><strong>me.record.questionaires:</strong></div>
    <div ng-repeat="q in me.record.questionaires">
    <div>{{q}}</div>
    </div>
  </div>
</div>

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

Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality. However, I am facing an issue where I want the two SVGs to align v ...

Creating a Loop for Tabs on an HTML Form

When navigating through form input boxes using the tab key, it usually goes in order. However, I discovered that you can actually customize this order by using tabindex=x. Since I have 5 inputs on my form, I use tabindex 5 times to specify the order. But ...

Is there a way to execute publish without automatically triggering postpublish?

I am working on a project that includes a specific postpublish action in its package.json. Recently, I encountered a situation where I need to run the publish command without triggering the associated postpublish action. Is there a foolproof method to exe ...

Errors in socket.on Listeners Result in Inaccurate Progress and Index Matching for Multiple Video Uploads

Is there a way to make sure that the `socket.on('upload-progress')` listener accurately updates the upload progress for each video as multiple videos are uploaded simultaneously? Currently, it appears that the listener is updating the progress fo ...

Deriving variable function parameters as object or tuple type in TypeScript

Searching for a similar type structure: type ArgsType<F extends Function> = ... which translates to ArgsType<(n: number, s: string)=>void> will result in [number, string] or {n: number, s: string} Following one of the provided solu ...

Using AJAX to assign PHP session variables

Is there a way to update the SESSION variable named "fullname" on Page 2 without causing the page to refresh? This is my attempt using AJAX: HTML code for Page 1: <input type="text" name="fullname" id="fullname" placeholder="Full name"> <butto ...

ES modules' `require()` functionality is not supported

Issue: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\...\node_modules\normalize-url\index.js [0] require() of ES modules is not supported. [0] require() of D:\...\node_modules\normalize-url\index.js ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

"Encountering issues with testing the controller of an Angular

I am facing difficulties while attempting to test a modal controller (developed using Angular UI Bootstrap). I simplified the test code as much as possible, but I keep encountering an error. Below is part of the modal controller: var controllersModule = ...

Unusual behavior observed in Selenium test (Python) when interacting with an Angular JS-based user interface

Currently, we are conducting tests on a web application that is built using AngularJS. I have come across an issue twice so far. This time, I am faced with the task of clicking on a dropdown menu within a link tag. While I can manipulate it manually using ...

Is it Necessary for Bower to Update a Package Frequently?

I seem to be encountering an issue while attempting to build with gulp (highlighted as the first problem). I've observed that every time I run "bower update bootswatch," something is being downloaded. As I am not very familiar with package management, ...

Modify the Embed Audio Player in Google Drive

I am looking to integrate audio files from Google Drive into my website. While I have successfully embedded them, the issue lies in not being able to customize the player (as shown in the image below). Is there a way to modify the player? <iframe ...

Switch Angular checkbox to display string values instead of boolean true/false

My task is to create three checkboxes in a form with values toggling between "optin" and "optout" as I check/uncheck the checkboxes. Additionally, all checkboxes should be checked by default for the "optin" value. I'm struggling to find a solution, an ...

What is the reason behind Typescript flagging a potential undefined value when checking for array length using a greater than comparison but not with an

Consider the following excerpt from a React component: const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => { const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : t ...

Develop a versatile JavaScript or jQuery script that automatically sets the focus on the first input field within a div or tag when the user clicks on it

I am currently working on creating a data entry form using a table layout. The form has two columns - the first column for input titles and the second column mostly for input tags. I styled the inputs in the second column to appear transparent with no bord ...

How about connecting functions in JavaScript?

I'm looking to create a custom function that will add an item to my localStorage object. For example: alert(localStorage.getItem('names').addItem('Bill').getItem('names')); The initial method is getItem, which retrieves ...

Interested in discovering the ins and outs of the JavaScript Map function?

Currently, I am delving into this JavaScript function: function solution (array, commands) { return commands.map (v => { return array.slice(v[0] -1, v[1]).sort((a, b) => a - b).slice(v[2] -1, v[2])[0]; }); } I am puzzled about th ...

Extract source, medium, etc. data from __utmz GA with the help of JavaScript

Is it possible to retrieve the campaign, source, and medium that Google Analytics records all at once when the page loads? If so, could I use jQuery to look up the values from __utmz? ...

Sorting elements to the beginning of each nested array

Looking to rearrange the elements in the given nested array, moving the element with the id 'cat_spc_my_special_id' to the top of the list using the keyword 'special'. There are 4 items currently in the above array, and the goal is to ...

Ways to show a corresponding number beneath every image that is generated dynamically

I have a requirement to show a specific image multiple times based on user input. I have achieved this functionality successfully. However, I now need to display a number below each image. For example, if the user enters '4', there should be 4 im ...