Transform a JavaScript object into a different structure

I need help converting a JavaScript object to another format.

For example, my input object in JavaScript looks like this:

$scope.name_person= [{
    "firstName":"Jean","lastName":"Smith"
 }]

The desired output should look like this:

 $scope.name_perso=  [{ 

  "values":[
       "firstName":"Jean","lastName":"Smith"
           ]
  }]

This is the code I have so far:

function convert(arr) {
    return $.map(unique(arr), function(name){
        return {
            values: $.grep(arr, function(item){
                return item.name == name
            })
        } 
    });
}

function unique(arr) {
    var result = [];
    $.map(arr, function(item){
        if ($.inArray(item.name, result))
            result.push(item.name);
    })
    return result;
}

$scope.data=convert($scope.name_person);

Any advice on improving this conversion process?

Answer №1

var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
  
  $scope.name_person= [{
    "firstName":"Jean","lastName":"Smith"
 }];
   var array = [{'values':[]}];
  angular.forEach($scope.name_person,function(item,i){
         array[0].values.push(item);
      });
  
  $scope.name_person = [];
  $scope.name_person = array;
  console.log(array);
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">

     <pre>{{name_person | json}}</pre>
</div>

give this a shot

  var array = [{'values':[]}];
  angular.forEach($scope.name_person,function(item,i){
     array[0].values.push(item);
  });

  $scope.name_person = [];
  $scope.name_person = array;

Answer №2

 $scope.personName=  [{ 

  "details":[
       "first":"Jean","last":"Smith"
           ]
  }]

If you want to create a key-value pair collection in JavaScript, you should use objects instead of associative arrays.

Here's how you can achieve this:

    var $scope = {};
    $scope.newObject = [];
    $scope.namePerson = [{
        "first":"Jean","last":"Smith"
    }];
    $scope.newObject.push(
        {
            "details": $scope.namePerson[0]
        }
    );

    console.log($scope.newObject);

The output will be:

[{ 
   "details":{
      "first":"Jean","last":"Smith"
       }
}]

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

Guide for utilizing regex to divide a string by various characters in the expression?

Apologies if the wording is unclear. I am currently looking for a solution on how to include a string match of multiple characters in my dynamic regex expression. The regex within my else statement successfully handles a single character input, now I am a ...

How can you retrieve the Adobe Marketing Cloud ID if cookies have not been set before using DTM?

Looking for a solution to capture the Adobe Marketing Cloud ID (MID) when a page loads using a Data Element or any other alternative method. The current Data Element logic works well if the Marketing Cloud cookie already exists. However, if there is no exi ...

JavaScript - Unexpected fluctuations in variable values

After studying Japanese language, I decided to try my hand at experimenting with JavaScript by creating a simple FlashCard game for a project. The game generates an array of random numbers, fills the divs with 6 possible choices using jQuery, randomly sele ...

AngularJS directive for automatically resizing Dygraph on page load

Could someone please assist me with resizing my graph inside tabs using Angular? When I initially load the graphs, they don't display unless I manually resize the window. How can I ensure that the graphs are loaded and fill the div on the first load? ...

Avoiding Socket IO from timing out when the browser page is inactive or not the focused tab on Google Chrome, Mozilla Firefox, and Safari mobile browsers

I have developed a basic chat application using socket io. The functionality is quite similar to the socket io chat official demo. However, I am facing an issue where Socket io times out on all mobile browsers when the user minimizes the page, opens anothe ...

How can I execute a HTTP POST request in Node.js using MongoDB and Mongoose?

I have completed my schema setup and now I am looking for guidance on how to perform an HTTP POST request. I am currently utilizing MongoDB with the Mongoose framework. By implementing this, I aim to view the JSON data I have posted when accessing localhos ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

Unauthorized access detected during ajax request triggered by onpaste event

Recently, I encountered an issue with my asp.net mvc website where an ajax call to the server stopped working in IE 11, despite previously working fine in IE 8. The error message pointed to an access denied exception in jQuery 1.7.1 at h.open(c.type,c.url, ...

unable to submit form using angular and express

I am encountering an issue with a post request in AngularJS to express. The HTML form on the client side is defined as follows: <div ng-controller="LoginCtrl"> <form ng-submit="login()"> <div> <label>Username</lab ...

The `XMLHttpRequest.prototype.open` function does not capture every single HTTP request visible in the chrome-dev-tools

While utilizing a third-party embedded code that initiates HTTP requests with a request header origin different from my own, I encountered an issue. Despite attempting to intercept these HTTP requests using XMLHttpRequest, they do not get intercepted. This ...

Implementing Jquery to attach a click event immediately after adding a new row to the table, all

I have an issue where I am adding a new row to my table. Within this row, there is a button that should be clickable and trigger an event. I have come across various solutions, but they all involve using the following code: .on('click', 'bu ...

Eliminate any values that have not been chosen from the dropdown array in ngx-select-dropdown

Scenario: The challenge involves managing selected values in Angular applications using the ngx-select-dropdown. Users can select multiple values, which are then sorted into "buckets" and sent to the API. Problem: I'm facing difficulty removing a sel ...

Tips for making an ajax call in Angular 6

As a backend developer, I have limited experience with Angular. How can I send an ajax request from Angular to test my API? The request needs to be sent before clearing the localeStorage. Can you provide guidance on how to achieve this? <button (clic ...

Building objects with attributes using constructor functions

My question pertains to JavaScript constructor function prototypes. Suppose I have code like the following: a = function (name){this.name = name}; a['b'] = function (age){this.age = age}; c = new a('John'); c.a['b'](30); Is ...

Errors occur when attempting to install plugins from npm

I am currently coding in Visual Studio 2017 using Ionic v2 to develop an app for beacon scanning. However, every time I try to install a plugin, I encounter errors from npm about the versions of node and npm being incompatible. Here are my current versions ...

Error encountered while trying to access `cookies.js` file in the `axios` module located at `../node_modules/axios/lib/helpers/`. The specific

Every time I attempt to retrieve data using axios.get(url), an error is thrown. Despite trying numerous solutions, nothing seems to work and this issue has persisted for quite some time. Any assistance that can be provided would be greatly appreciated. Er ...

pattern validation using a regular expression

I am just starting to learn about regular expressions. In my current project, I am allowing users to input amounts in both shorthand and full digit formats using a material UI TextField component. Here are some examples of the input formats: 400k - short ...

The $scope variable fails to reflect updates in the view following a broadcast event triggered by a

I have been troubleshooting a similar issue and I can't seem to figure out why the update is not reflecting in the view. While I am able to see the scope variable updating in the catch events logs, the changes are not being displayed in the view. For ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

When a table is required, .data() will provide a string

Within my HTML code, there is a table structure defined as follows: <table id="table" data-keys="{{keys}}"> Here, the keys variable represents an array (as I later iterate through it using {% for k in keys %}). However, when I t ...