Using JavaScript in Ext JS 4, transform a JSON object into a different JSON object

What is the simplest way to transform JSON A into JSON B using JavaScript?

JSON A:

{
    "d":
    [
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"one"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"1","value":"two"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"2","value":"three"}
    ]
}

JSON B:

{
    data:
    [
        {"key":"1", "value":"one"},
        {"key":"2", "value":"two"},
        {"key":"3", "value":"three"}
    ]
}    

===================

Update on 8/1/2012 (solution for Ext JS with ASP.NET proxy):

I didn't mention the JavaScript framework I was using in my original question, but it appears that by setting the root property value to "d" you can effectively remove the "d" key.

var statusDropdownStore = new Ext.data.Store({
    proxy: new Ext.ux.AspWebAjaxProxy({
        url: '/track/Controls/Shared/GeneralService.asmx/GetDropdownOptions',
        actionMethods: {
            create: 'POST',
            destroy: 'DELETE',
            read: 'POST',
            update: 'POST'
        },
        extraParams: {
            user_login: authUser,
            table_name: '[status]'
        },
        reader: {
            type: 'json',
            model: 'DropdownOption',
            root: 'd'
        },
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        }
    })
});

Proxy:

Ext.define('Ext.ux.AspWebAjaxProxy', {
    extend: 'Ext.data.proxy.Ajax',
    require: 'Ext.data',

    buildRequest: function (operation) {
        var params = Ext.applyIf(operation.params || {}, this.extraParams || {}),
                                request;
        params = Ext.applyIf(params, this.getParams(params, operation));
        if (operation.id && !params.id) {
            params.id = operation.id;
        }

        params = Ext.JSON.encode(params);

        request = Ext.create('Ext.data.Request', {
            params: params,
            action: operation.action,
            records: operation.records,
            operation: operation,
            url: operation.url
        });
        request.url = this.buildUrl(request);
        operation.request = request;
        return request;
    }
});

Combo Box (dropdown) configuration:

                    {
                        xtype: 'combo',
                        fieldLabel: 'Status',
                        emptyText: 'Select a status...',
                        store: statusDropdownStore,
                        valueField: 'key',
                        displayField: 'value',
                        mode: 'remote',  // or 'local'
                        renderTo: document.body
                    },

Answer №1

Below is an example:

var sample = {
    "info":
    [
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"apple"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"1","value":"banana"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"2","value":"orange"}
    ]
};

sample.data = sample.info;
delete sample.info;
for(var j=0,n=sample.data.length;j<n;j++){
    delete sample.data[j].__type;
}

Answer №2

Here is a possible solution:

var parsedJson = JSON.parse(JsonA);
parsedJson = parsedJson.d;

var newJson = [];
var newObj = {};

if (parsedJson.length > 0) { 

  for (var i = 0, loopTimes = parsedJson.length; i < loopTimes; i++) {
      newObj = {};
      newObj.key = parsedJson[i].key;
      newObj.value = parsedJson[i].value;
      newJson.push(newObj);
  }
}

parsedJson = null; // if you need to discard the initial object

In addition, I believe JsonB should be an array of objects, rather than an object containing an array of objects like this:

[
     {"key":"1", "value":"one"},
     {"key":"2", "value":"two"},
     {"key":"3", "value":"three"}
]  

Answer №3

If you're facing this issue, you can consider following the steps mentioned in - which involves utilizing the delete function to eliminate the key.

One approach is to iterate through the array and apply the delete method, followed by renaming the array (by introducing a new attribute and then removing the old one).

Answer №4

give this a shot :) http://jsfiddle.net/daewon/LnpXb/

var jsonData = {
    items: [
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"apple"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"1","value":"banana"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"2","value":"cherry"}
   ]
};

var newData = {
    data: []
};

var items = jsonData.items;
for (var j=0; j<​items.length​; j++){
    var object = {
        key : items[j].key,
        value : items[j].value
    };

    newData.data.push(object);    
}
console.log(JSON.stringify(newData));
=> {"data":[{"key":"0","value":"apple"},{"key":"1","value":"banana"},{"key":"2","value":"cherry"}]} 

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

Achieving multiple validations on a single element in AngularJS, along with the ability to validate

Currently, I am in the process of constructing a form and utilizing the built-in AngularJS validation objects to validate the form. The following is an overview of my form: <form name="myForm" ng-submit="DoSomething()" novalidate> <te ...

Position an element with absolute positioning to the right edge of a relative element

I have a situation where I need to align the end of a position absolute element with the end of a relative element, but the relative element's width is not fixed and may vary based on content. https://i.sstatic.net/L2sLP.jpg This scenario arises as ...

The myAjax variable is not defined within WordPress

Currently, I am working on a child theme and have implemented the following code for admin ajax JS: function wpb_adding_scripts() { /* echo "string". get_stylesheet_directory_uri().'/css/jquery.bxslider.css'; exit();*/ wp_register_scrip ...

Assigning nested JSON values using Jquery

My JSON data structure is as follows: { "Market": 0, "Marketer": null, "Notes": null, "SalesChannel": null, "ServiceLocations": [ { "ExtensionData": null, "AdminFee": 0, "CommodityType": 0, ...

Sending data from a PHP function to an AJAX call in the form of an associative array using json_encode() does not

Greetings, this is my first post so please forgive me if I miss anything or fail to explain clearly. All the code below is within the same PHP file. Here is my AJAX call: $.ajax( { type: "POST", url: window.location.href, data: {func: 'g ...

What exactly does the dollar sign signify in plain JavaScript code?

While watching a tutorial on object literals in JavaScript, I noticed something interesting. The instructor demonstrated creating an object like this: var Facebook = { name: 'Facebook', ceo: { firstName: "Mark", favColor: ...

How can you rearrange the order of objects in an array to only include duplicates?

https://i.sstatic.net/XwCDZ.png I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an ad ...

Show the JSON data from the server in a table format

Is there a way to neatly display data received from an Ajax response within a table format? Below is the structure of the table: <table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table"> ...

Is it possible to retrieve a particular JSON value based on its unique identifier?

I am seeking to retrieve the date associated with typeId: 11 from the given JSON data. Since the order of typeId's varies, simply targeting the second value may not always work. { "page": 1, "totalsCount": 1, "i ...

Basic HTML and JavaScript shell game concept

After spending several days working on this project, I am struggling to understand why the winning or losing message is not being displayed. The project involves a simple shell game created using HTML, JavaScript, and CSS. I have tried reworking the JavaSc ...

Creating an Array of dynamically generated elements using jQuery

A dynamic table is being generated using jQuery's .append() function: $el.append('<tr data-id=' + data[i].id + ' data-token=' + data[i].token + '><td>' + data[i].order + '</td>\n\<td&g ...

What is the connection between importing and using destructuring in ES6 syntax?

Bring in: import React, { Component } from 'react'; Unpacking: let z, { b } = {a: 1, b: 2, c: 3} Both of these examples seem to have similar syntax. However, in the second example, z will be undefined instead of {a: 1, b: 2, c: 3}. Does this ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

Connect jQuery navigation button to a specific web address

Check out this cool jQuery menu script I found: <script type="text/javascript> jQuery(document).ready(function(){ jQuery('#promo').pieMenu({icon : [ { path : "/wp-content/t ...

Using Python to convert a data frame into a nested dictionary

Currently, I have a dataframe structured like this: day account_id balance 2022-11-01 ncw8y7 1.000000 2022-11-02 ncw8y7 1.000424 My goal is to convert it into a nested dictionary format where the first level represents the acco ...

The functionality of Vue JS v-attr="expression1 && exp2 && exp3" seems to be malfunctioning

Why aren't Vue JS v-attr=“expression1 && exp2 && exp3” working? I've attempted using ${&}${&}, #{&}#{&}, &amp;&amp;, and even #{&amp;}#{&amp;} The code can be found on JSFiddle <div id="dem ...

Using the Volley library, you can retrieve specific data from a list view by clicking on a particular item

If I click on a particular item in the list view, how can I retrieve specific data using the Volley library? I am currently utilizing the Volley library to populate a list view with images and text. Each item in the list contains an image and accompanying ...

Cancel an AJAX request without interfering with the subsequent request

When working with a number input and the "onChange" event, I have come across an issue with my ajax request. Upon aborting the request, it seems to have a negative impact on subsequent requests. If I send just one request without aborting, everything runs ...

JSON objects not loading properly in Bootstrap table

I am facing an issue where my ajax script successfully sends JSON objects to the browser, but the table fails to load the JSON object. Here is my Ajax script: $.ajax({ type : "POST", url : "getLabels.jsp", data : "mail ...

The Google Maps application is having trouble zooming in

I'm having trouble with my function that takes the zoom level and sets the center of the map. When I call setCenter with my positional coordinates and zoom level, the map doesn't zoom in where I want it to. However, the position of my info window ...