What is the best way to concatenate JSON in JavaScript?

How do I merge this JSON data accordingly:

complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"]
?

Each address may have multiple complements that need to be combined and separated by a comma.

Note: JavaScript is being utilized. Note 2: Complements can be empty as shown in the second group of JSON.

[
    {
        "postalcode": "1234",
        "street": "ABC",
        "number": "1",
        "complement": [
            {
                "type": "B",
                "name": "XYZ",
                "description": "3"
            },
            {
                "type": "C",
                "name": "CDE",
                "description": "TR"
            },
            {
                "type": "D",
                "name": "AAA",
                "description": "5"
            }
        ]
    },
 {
        "postalcode": "444",
        "street": "No complements",
        "number": "5"
    },
    {
        "postalcode": "2222",
        "street": "BBB",
        "number": "2",
        "complement": [
            {
                "type": "E",
                "name": "NDP",
                "description": "3"
            },
            {
                "type": "F",
                "name": "DDD",
                "description": "FR"
            }
        ]
    }
];

My code I'm encountering this.complementsList.forEach is not a function.

getComplement(addressesResponse){
    this.complementsList = JSON.parse(addressesResponse);

    this.complementsList.forEach((item) => {
    Object.defineProperty(item, 'complements', {
        get: function() { 
            return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
    })
});

Source:

Answer №1

My strategy for finding a solution :

arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');

Answer №2

One way to manipulate a javascript object is by iterating through its keys and combining specific ones into strings.

Here's some example code:

const data = [{...}, {...}, ...]
const results = [];

data.forEach((item) => {
  let result = item['specificKey'].reduce((total, currentObject) 
     => total += (currentObject.name+' '+currentObject.description), "");
  results.push(result);
});

This is just one method among many that can accomplish the task.

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

Store a pandas DataFrame in a compressed file object using gzip encoding

I have been attempting to save a pandas DataFrame into an in-memory json_buffer and then load the file to S3 using the code below: json_buffer = StringIO() df.to_json(json_buffer, orient='records', date_format='iso', compression='g ...

What is the best way to display form input fields depending on the selected value?

I've been struggling with a seemingly simple issue that I can't seem to find the right solution for, even after scouring Google. I have a form field for input and a select field with various values, including an "Other" option. Here's what ...

In Vue, applying CSS styles to D3's SVG elements may not work as expected when using the scoped attribute

Here is the code snippet of my component: <template> <div id="something" class="card"> </div> </template> const height = 200; const width = 200; let graph = d3 .select('#something') .append('svg') ...

Techniques for transferring images directly into HTML canvas games

I created a thrilling race car game and here is the code snippet: index.html <!DOCTYPE html> <html> <head> <title> Extreme Race Car Game </title> <link rel="stylesheet" type="text/css" href="style.css"> < ...

Hide a div using jQuery and then reveal it when clicked

I am trying to create a sliding effect for a div that appears behind another div when an arrow is clicked, and then hides again when a form button is clicked. While I can code most of this functionality, I am struggling with the specific implementation of ...

Angular failing to update $scope variable within controller

I need to implement a directive that allows file uploading directly to the browser angular.module('angularPrototypeApp') .directive('upload', ['$parse', function ($parse) { return { restrict: 'A', scope: fal ...

Trouble with AJAX request when trying to connect to a distant server

I am facing an issue with my AJAX request. When I test it on localhost, everything works perfectly fine. However, when I upload the code to a remote server, the request fails without any error messages. Even after checking in Firefox and Chrome, there ar ...

Using Django Rest Framework to Serialize Multiple Models

How can I send this JSON via POST? { "campaign": 27, "campaignName": "Prueba promo", "promotionType": 999, "items": [ { "item_nbr": 1234567890123, "plu": 2}, { "it ...

Tips for extracting data from a JSON response containing an unnamed array of objects

I need help with parsing a JSON result that does not have an array name specified. Below is the JSON response I am working with: [ { "Id": 2293, "Name": "Dr.", "Active": true }, { "Id": 2305, "Name": "Mr ...

Getting the URL for a downloaded image using ImageLoad on Android

I encountered an issue with my Android application In the database, I stored URLs of some images and now want to download these images for a viewpager display using ImageLoader. The problem arises when trying to download the image URLs from the server. I ...

Tips for patiently awaiting the completion of an API's creation and local audio file writing process prior to uploading it to an S3 bucket

I am currently utilizing an API to generate a TextToSpeech audio file on the local filesystem before uploading it to an S3 bucket. The package I am using for this process is called elevenlabs-api. The issue I am facing is that the code fails because it ta ...

Enhance your website with a dynamic 'click to update' feature using ajax

I'm in the process of developing a straightforward list application where users can easily edit items by clicking on them. Although everything seems to be working fine, I'm encountering an issue with saving changes to the database. For some reaso ...

PHP code throwing error when trying to store JSON data in database

I'm a beginner in PHP and I'm trying to send a JSON string via POST containing an array list of products from Android to a PHP webservice. However, when I try to var_dump the decoded array, it shows null. Here is my code: <?php $servername = ...

Is it possible to achieve a Column Chart output in R/Highcharts?

Looking to utilize highchart to create a chart with columns stacked within each other for different countries. https://i.sstatic.net/2p1uM.png I want the smaller column to be nested inside the larger one for each country. Any suggestions on how I can ac ...

Tips for effectively passing "this" to direct the event initiator in react js?

I'm facing an issue where I am attempting to send a buttons object to a function and then access its properties within that function. Here's my button : <RaisedButton label="Primary" id = "1" onTouchTap={()=>this.buttonPress(this)} prima ...

Expanding a React component passed through the Redux connect() function

Is there a method to extend a component connected by the Redux connect() function? For instance, if I am working within the form-container.js and using const FormContainer = connect( mapStateToProps, mapDispatchToProps )(Form) Can I override meth ...

I require assistance with parsing the JSON outcome within a C# Windows Phone application

As a newbie in the world of developing Windows Phone apps, I am facing an issue that has been persistent even after trying out all possible solutions. The problem arises when my application tries to retrieve data from a web service, and the result it recei ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

Transferring cookies across subdomains

I am facing an issue with an ajax request going from one subdomain to another, for example from sub1.example.com to sub2.example.com. Despite having a cookie set for all domains (cookie domain='.example.com'), the cookie is not being sent to the ...

.forEach returns an undefined value for each length

Having trouble with my if statement. It seems like the else block is working fine, but the if section is not functioning as expected. The variable count1 comes out as undefined. Interestingly, the conditions inside the if statement are working correctly ...