Changing an object to an array in Angular

As a newcomer to javascript and angular, I am facing a challenge. I have a JSON object like this: {"xyz":{Key:info}}. My goal is to add {Key:info} into an array.

Specifically, I want to transform "xyz" into an array format. For example: {"xyz":[{Key:info}]} This way, I can easily push multiple instances of {Key:info} into that array - like this:

{"xyz":[{Key:info},{Key:info},{Key:info}]}
.

In addition, I need to ensure that if xyz is originally an object, it gets converted into an array and only one instance is pushed in.

My struggle lies in figuring out how to accomplish this using angular javascript.

EDIT :- Added original JSON

$scope.ContentObj= {
      "attribute-set": [
        {
          "attribute": [
            {
              "_name": "text-align",
              "__prefix": "xsl",
              "__text": "end"
            },
            {
              "_name": "end-indent",
              "__prefix": "xsl",
              "__text": "10pt"
            }
          ],
          "_name": "odd__header",
          "__prefix": "xsl"
        },
        {
          "attribute": {
            "_name": "font-weight",
            "__prefix": "xsl",
            "__text": "bold"
          },
          "_name": "pagenum",
          "__prefix": "xsl"
        }
      ],
      "_version": "2.0",
      "__prefix": "xsl"
    }

Answer №1

To determine if something is an object, you can utilize the typeof method and then extract its content to initialize an array with it

let myObject = {"xyz":{Key:"info"}};

if(typeof myObject.xyz === "object"){ //Check for object type
  const content = myObject.xyz; //Extract content
  myObject.xyz = [content]; //Store content in an array
}

console.log(myObject);

If this is required in your code based on the comments:

if(typeof $scope.ContentObj.stylesheet["attribute-set"][4].xyz === "object"){ //Check for object type
  const content = $scope.ContentObj.stylesheet["attribute-set"][4].xyz; //Extract content
  $scope.ContentObj.stylesheet["attribute-set"][4].xyz = [content]; //Store content in an array
}

console.log(myObject);

Answer №2

Here is a potential solution for your question.

if (!angular.isArray($scope.yourObject.xyz)){
    $scope.yourObject = {
        xyz: []
    }
}
$scope.yourObject.xyz.push({Key:'info'})

Answer №3

Here is an alternative approach.

$scope.yourObject.xyz.push(Object.assign([], yourObject))

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

Reverse the Order of a Text File, Starting from the First Entry

I find it quite strange that no one has brought up this particular question before, as it has been gnawing at me for hours. Here's the issue I'm currently grappling with: My task involves reversing the order of a text file, displaying the last 1 ...

Is there a way to implement a feature that automatically closes the chatbot when the user clicks outside of it?

Here is an example of my HTML code: <div class="chatbot chatbot--closed "> <div class="chatbot__header"> <p><strong>Got a question?</strong> <span class="u-text-highlight">Ask Harry</span></p> < ...

Ways to retrieve a converted document using the Microsoft Graph API

I'm encountering an issue when trying to save a PDF file received from the Microsoft Graph API. The call I am making looks like this: const convertConfig = { headers: { Authorization: <my token> } }; convertConfig.headers['C ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

generate an array with multiple dimensions

Currently, I am involved in managing a hotel reservation system where the rates are calculated per night. The database comprises two main tables: stock and promotions. The stock table includes a row for each day of the year (365 days), while the promotions ...

Utilizing margins in CSS for various div elements

Update: I have included Javascript and Masonry tags in my project. Despite having modules of the same size, I am exploring how masonry can assist me. However, I find it a bit puzzling at the moment as I am not aiming to align elements of different sizes. I ...

Displaying queries using ajax in Rails

Can someone assist me in dealing with a particular issue? I am using ajax to refresh queries from the database dynamically each time there is a change in a search form. The main objective is to load N number of records based on the parameters selected in ...

Learn the simple steps to duplicate events using ctrl, drag, and drop feature in FullCalendar v5 with just pure JavaScript

My goal is to incorporate CTRL + Drag & Drop functionality in FullCalendar v5 using nothing but pure JavaScript. I delved into the topic and discovered that this feature has been discussed as a new UI feature request on the FC GitHub repository. There ...

What is preventing me from retrieving the accurate date from the array?

https://i.sstatic.net/22zSb.pngWhy is it that I am unable to retrieve the correct date from the array? I have attempted to extract the accurate date from the array using Log.d methods. While the date is present in the array, whenever I click the listener, ...

Tips for using JavaScript to set images from Flickr API as img src

I've been attempting to populate a table with images fetched from flickr. The array I'm using consists of urls like: ["https://www.flickr.com/photos/113081696@N07/24695273486", "https://www.flickr.com/photos/113081696@N07/24565358002", "https:// ...

Retrieving PHP information using Javascript and storing it in an array

I have a PHP script that fetches data from a server and stores it in an array. I then convert this array into a JSON object using the following function: echo json_encode($result); Now I want to access this array in my JavaScript and display it. I want t ...

Using Jquery Ajax in Conjunction with Spring MVC

I recently encountered an issue while trying to make an ajax query from a Spring MVC JSP page. The request was successfully made and I could see the JSON response on the browser. $.get("${pageContext.request.contextPath}/xxx.htm", {x: y}, function(result) ...

Converting Blob to Base64 using javascript

I've managed to successfully convert my base64 (DATA_URI) image into a blob, but I'm facing issues with reverting it back. Here's what my base64 to blob code looks like for better understanding. Check out this link. b64toBlob(b64Data, cont ...

Utilizing an Array to Implement Picture Slideshow Effects in a UIScrollView

As a newcomer to iOS development, I have been browsing through various posts on this platform and on Google in search for a solution to what seems like a simple issue. Despite my efforts to learn and create my own code with unique logic, I seem to be facin ...

Can JSON be parsed: Checking for the existence of a JSON key

I am using an API REST to request a JIRA filter in Excel and receive the result in a JSON object. I am parsing this object and attempting to display the result in a message box. However, I encounter an issue when the JSON key does not exist! Here is an e ...

Differences in SVG rendering between Chrome and Firefox

I am eager to create a diagram on my website using SVG. To ensure the diagram is displayed in full screen, I am utilizing availHeight and availWidth to determine the client screen's height and width, then adjust the scaling accordingly. My current sc ...

What is the functionality of the reduce() higher-order function?

Here is the reduce() function implementation: function reduce(array, combine, start) { let current = start; for (let element of array) { current = combine(current, element); } return current; } Now, I am tackling this question: ...

Trigger the select dropdown when a key is clicked

I am currently working on a project in react where I am utilizing the Select component from material. When I open the dropdown and press a key on my keyboard, the option starting with that key gets automatically selected. This behavior is also observed in ...

Inheritance through Parasitism in JavaScript

Just finished a Douglas Crockford lecture where he introduced the concept of parasitic inheritance in JavaScript. This involves one constructor calling another to modify the object. The code example he provided is: function gizmo(id, secret) { secret = ...

"Troubleshooting the issue with AngularJS custom directive failing to load initially

If you want to view the live example here, you may or may not be in for a surprise - as it may not be functioning properly. Essentially, I am endeavoring to create a personalized directive named yesno-group. This is intended to simplify the repeated task ...