Transforming items into an array

Creating a JSON object with the following structure is something I'm trying to accomplish:

    {
        "PROMO": {
            "ID": 1,
            "NAME": "PROMO ONE",
            "BUNDLES": {
                "0": {
                    "BUNDLE": {
                        "BUNDLE_ID": 1,
                        "BUNDLE_NAME": "BUNDLE ONE"
                    },
                    "ARTICLE": {
                        "ARTICLE_IDS": "550,398,475"
                    }
                },
                "1": {
                    "BUNDLE": {
                        "BUNDLE_ID": 1,
                        "BUNDLE_NAME": "BUNDLE ONE"                    
                    },
                    "ARTICLE": {
                        "ARTICLE_IDS": "125,250,323"
                    }
                }
            }
        }
    }

My goal is to merge the BUNDLE and ARTICLE objects and then add them to the BUNDLES array. I have been unsuccessful in my attempts to combine the two objects.

I have attempted the following approach:

var BUNDLES = [];
var BUNDLE = {};
var ARTICLE = {};

BUNDLE.BUNDLE_ID = 1;
BUNDLE.BUNDLE_NAME = "BUNDLE ONE";
ARTICLE.ARTICLE_IDS = "550,398,475";

// Here, I aim to merge ARTICLE and BUNDLE before pushing into the array
BUNDLES.push(BUNDLE)

Answer №1

Here is a solution that should meet your needs. While there may be more elegant approaches, this code achieves the desired outcome.

http://jsfiddle.net/558BN/

var json =    {
        "PROMO": {
            "ID": 1,
            "NAME": "PROMO ONE",
            "BUNDLES": {
                "0": {
                    "BUNDLE": {
                        "BUNDLE_ID": 1,
                        "BUNDLE_NAME": "BUNDLE ONE"
                    },
                    "ARTICLE": {
                        "ARTICLE_IDS": "550,398,475"
                    }
                },
                "1": {
                    "BUNDLE": {
                        "BUNDLE_ID": 1,
                        "BUNDLE_NAME": "BUNDLE ONE"                    
                    },
                    "ARTICLE": {
                        "ARTICLE_IDS": "125,250,323"
                    }
                }
            }
        }
    }

var array = [];
for(var i in json.PROMO.BUNDLES){
    var obj = {};
    for(var j in json.PROMO.BUNDLES[i]){
        obj[j] = json.PROMO.BUNDLES[i][j]
        //console.log(j + " " + obj[j]);   
    }
    array.push(obj);
}
json.PROMO.BUNDLES = array;
console.log(json.PROMO.BUNDLES);

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

How can you effectively transfer arguments from one component to another using router.push() in Vue.js?

I need help with implementing a feature where upon clicking the edit button in a row, all the details from that particular row should be passed to a form component. I want to populate the form fields with default values from the parameters provided. Can ...

The content of btn-id element in Angular is showing as undefined

I have a JavaScript file located at sample/scripts/sample.js and there are 8 HTML files in the directory sample/src/templates/. My goal is to select a button on one of the HTML files. When I tried using angular.elemnt(btn-id).html(), I received an 'un ...

Another problem with CORS again?

My rails application uses the host http://myhost.dev to search for music through the vk.com API. The API provides a search method called audio.search. Below is the code snippet from my search.js.erb file which is executed via a remote link to the search ac ...

What is the Most Effective Way to Arrange an Array of Objects Based on Property or Method?

Looking for ways to enhance my array sorting function, which currently sorts by property or method value. The existing code is functional, but I believe there's room for improvement due to redundant sections. optimizeSort(array: any, field: string): ...

Ways to guarantee that a function runs prior to a console.log in Mongoose

I've created a function called findUser that I'm working on implementing using sails, MongoDb, and mongoose. Here's what the function looks like: findUser(userId); function findUser(user_id){ User.findOne({ _id: user_id ...

Ensure that the jQuery datepicker is set with a maximum range of 365 days between the two input fields

Setting Up jQuery Datepicker Inputs I have implemented two jQuery datepicker inputs with default settings as shown below: $("#polis_date_from").datepicker({ uiLibrary: "bootstrap4", changeYear: true, changeMonth: true, dateFormat: "yy.mm.dd", ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...

Utilizing a range input (slider) to extract data of importance

When dynamically adding a slider to a page using a specific string, like the one shown below: "<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>"; After appending it to the page with pure JavaScript, ...

Removing a specific item from a Kendo UI dropdown list

Recently, I encountered a predicament with a dropdownlist populated from a datasource. Following a certain event, my goal is to eliminate a single item from the dropdownlist identified by id = 22. Although I recognize this may not be the best practice du ...

The jQuery AJAX autocomplete result box is either too cramped or displaying numbers

I'm having some trouble setting up jQuery UI autocomplete with ajax in my project using CI 3.1.5. When I try to implement it, I either get a small result box or just the number of results. Here is my AJAX code snippet: $(".addClient").each(funct ...

Replace HTML elements with AJAX and JavaScript

Working with MySQL data in pyramid presents a challenge as I need to dynamically change an HTML if statement based on the results from JS ajax calls. The main page receives data from views.py and passes it to the .mak script. The key views here are the ma ...

Is it possible to change XML using Ajax technology?

Is it possible to update a value in an XML file using JavaScript/Ajax? I've managed to access the XML file with Ajax and utilize its values in my script. Now, I want to send any updates made by the script back to the XML file on the server using Ajax ...

Searching for a name in JSON or array data using jQuery can be accomplished by utilizing various methods and functions available

Having trouble searching data from an array in jQuery. When I input Wayfarer as the value for the src_keyword variable, it returns relevant data. PROBLEM The issue arises when I input Wayfarer Bag as the value for the src_keyword variable. It returns em ...

Rendering data from an API using v-if

Could you help me change the tag that currently displays true or false? I want it to show "FREE" if the event is free and "PAID" if it's not. Check out the Eventbrite API here The response I'm receiving from data.events.is_free is in boolean fo ...

Selecting middleware to be executed based on Express JS request parameters

Can someone please advise me on how to select between two distinct middleware functions, based on the request for a specific endpoint? It may involve something along these lines: router.post("/findAvailableAgents", chooseMiddleware(middleware1, ...

Resource loading unsuccessful: server encountered a status of 500 (Internal Server Error)

I'm struggling to figure out why I keep getting an Internal Server Error when trying to call a web service in my HTML page using JavaScript and Ajax. Here is the error message: Failed to load resource: the server responded with a status of 500 (Int ...

Using PHP to dynamically update image source upon clicking an upload button:

Is it possible to dynamically display a new image after uploading it using an ajax-upload script on a 'edit product' page for a shop products? On load, all thumbnails are fetched from the DB but when a user uploads a new file, I want the new imag ...

Steps for Implementing a Delay on Bootstrap Dropdown Hover

Is there a way to create a delay for the bootstrap dropdown feature while ensuring that it still appears on hover? If you want to test this, click here: http://www.bootply.com/YcVBzvXqrR This is the HTML code I'm using: <div class="container"&g ...

Vue modifies the array in the data after creating a duplicate of it

Here is the Vue code snippet I'm working with: export default { name: 'Test', data() { return { test1: ['1', '2', '3'], test2: [{ name: 'Hello' }, { name: &apo ...