Ways to create a fresh framework for organizing data according to its values

Here is a JSON object that I need to restructure:

[
    {
      'con': 'Usa',
      'city': 'ny',
      'town':'as'
    },
    {
      'con': 'Ger',
      'city': 'ber',
      'town':'zd'
    },
    {
      'con': 'Usa',
      'city': 'la',
      'town':'ss'
    }
  ]

I want to organize this JSON into a new structure where no two objects have the same 'con' value. The desired structure should look like this:

[{
        "con": "usa",
        "area": [{
            "city": "ny",
            "town": "as"
        }, {
            "city": "la",
            "town": "ss"
        }]
    },
    {
        "con": "ger",
        "area": [{
            "city": "ber",
            "town": "zd"
        }]
    }
]

Do you have any suggestions on how to achieve this transformation? Thank you!

Answer №1

An alternative approach involves utilizing the Array.prototype.reduce method for grouping by country, combined with the Object.values function to extract the grouped objects.

let arr = [{    'con': 'Usa',    'city': 'ny',    'town': 'as'  },  {    'con': 'Ger',    'city': 'ber',    'town': 'zd'  },  {    'con': 'Usa',    'city': 'la',    'town': 'ss'  }],
    result = Object.values(arr.reduce((a, {con, ...rest}) => {
      (a[con] || (a[con] = {con, area: []})).area.push(rest);
      return a;
    }, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Improving HTML coding with a more effective alternative to document.write()

Looking at the setup of my website, I have a menu button and comments section that need to appear on every page. Instead of manually adding this code to each HTML file, I decided to streamline the process by using a JavaScript file that generates all of th ...

Uncertain about how to handle JSON data

Currently developing a weather app for Android in Eclipse, I need to display weather icons at 3-hour intervals over a 24-hour period. Using the API from Utilizing to generate Java classes (I believe that's its purpose..) Here is the code snippet: ...

Is there a way to pass a complete image element as a prop in React?

I am receiving a JSON response with an image property for each key. This image property contains the entire image element tag with properties. I am trying to pass this down to a child component, but when I attempt to render it, it only displays as plain ...

What could be causing the "Circular structure to JSON" error in Node.js when executing a MySQL query?

Currently, I am working on executing a MySQL query to retrieve all the data from a table named LOGIN. If you navigate to https://localhost:2000/select, and provide the parameter in the req.body as table_name with the value set as login. When making t ...

Exporting methods/functions in React Native

import { width as responsiveHeight } from "react-native-responsive-dimensions"; I am trying to export responsiveHeight with the name width. Can someone please guide me on the correct way to do this? The current approach is not yielding any results. ...

How to run a PHP script using JavaScript?

I am planning to execute a quick php script once users exit my website. Moreover, I am looking to transfer a variable from my javascript to php, but I am unsure how to integrate the php file and pass it a variable. Unfortunately, the php script is not runn ...

Using jQuery to extract data from an unnamed JSON array item

I am exploring ways to utilize JSON feeds and showcase them on PHP pages. While I have gained considerable knowledge from various examples, I am facing a challenge in dealing with arrays that do not have specific names or IDs for each field. For example: ...

Is there a way to prevent jQuery.ajax() from displaying errors in the console?

I have set up a jQuery JSONP request to monitor the status of a resource based on its URL. In case the resource is not accessible or the server goes down, my ajaxFail() function takes care of updating the display. function fetchServerStatus(service, host) ...

Page can be accessed using file_get_contents function but not with cURL

In the process of creating an API endpoint in PHP, a scenario arose where JSON data output from a specific page example.com/stats was causing issues with cURL requests compared to using file_get_contents(). How can I ensure that JSON data served in PHP is ...

What is the best way to extract information from this JSON data using JSON.NET?

Looking at my JSON data, it appears to be valid but slightly unusual. Here's how it's structured: { "server":"some server name", "files": { "filename1":{"source":"original","format":"text"}, "filename2":{"source":"original","format":"text"}, "fi ...

Using Ruby to access an array of hashes grouped by two attributes in order to iterate with the "take_while" method

Here is an array structure containing hashes: tasks = [{:id=>19, :position_id=>3, :value=>2.55, :from=>2017-09-04 18:00:00 +0300}, {:id=>10, :position_id=>3, :value=>0.16, :from=>2017-09-04 06:00:00 +0300}] In addition to ...

What is the best way to combine objects that share the same id?

View Image: Displaying Image POST ID's https://i.stack.imgur.com/JO5OF.png I attempted to resolve this using jQuery each, but I am uncertain about the next steps. Check out my Code: jQuery(document).ready(function($) { var data, exampleData, , ...

Using THREE.js to incorporate a stroke above extruded text

Looking to enhance text with a horizontal line above it: var geo = new THREE.TextGeometry("x", geometry_options); var mat = new THREE.MeshBasicMaterial({color: 0, side:THREE.DoubleSide}); geo.computeBoundingBox (); var vec = new THREE.Shape(); vec.moveTo( ...

Building a JavaScript application with Node.js and MySQL to seamlessly interact with both offline and online databases

As I develop a JavaScript web-app, my plan is to utilize Node.js for connecting the app with an existing MySQL database. My initial question pertains to the structure of the Node code: should it be written in the same .js file as my application or kept se ...

When trying to log the parsed JSON, it unexpectedly returns undefined even though it appears to be in good

Everything was working fine until a couple of days ago. Let's consider this as my PHP script: echo json_encode(array('stat'=>'ok')); I am sending an AJAX request to this script: $.post(base_url+'line/finalize/', {t ...

If the PHP variable evaluates to true, then a CJuiDialog in Yii view will open

I am attempting to open the CJuiDialog if the $check value equals true in the view part. <?php if($check==true) { js:function(){$('#dialogDisplay').dialog('open');} } $this->beginWidget('zii.widgets.jui.CJuiDialog', ...

Executing jQuery script on dynamically loaded content

My website utilizes AJAX requests to load pages dynamically. One specific page includes a marquee script that I would like to implement. Unfortunately, due to the dynamic loading of the page, the marquee script is not functioning as expected. I have come ...

What steps do I need to take to integrate Twilio's SMS service into an HTML document?

I have been searching for solutions using php and node.js (which is a derivative of js, so it should work), but I came across this library: <script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js"></script> ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...