Simplify nested JSON data

I'm struggling with a JSON object that looks like this:

const people = {
name: 'My Name',
cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
}

What I need is the output to be formatted like this: each city flattened into an array.

[
  ['My Name', 'London', 'UK'], 
  ['My Name','Mumbai', 'IN'],
  ['My Name','New York', 'US']
]

I've tried using flatten without success. Can someone please assist me with this? Thanks, Sasi

Answer №1

Here's a nifty solution!

const persons = {
  name: 'My Name',
  locations: [{city: 'Paris', country: 'France'},{city: 'Tokyo', country: 'Japan'},{city: 'Sydney', country: 'Australia'}],
}

function flattenObject(obj) {
  const personName = obj.name;
  const locationData = obj.locations;
  return locationData.map(({city, country}) => [personName, city, country])
}

console.log(flattenObject(persons));

Answer №2

For JSON output, follow these steps:

const team = {
  name: 'My Team',
  players: [{player: 'Player 1', position: 'Forward'},{player: 'Player 2', position: 'Midfield'},{player: 'Player 3', position: 'Defender'}],
}

let roster = team.players.map(info => {
  return {
    name: team.name,
    player: info.player,
    position: info.position
  }
})

console.log(roster)

To expand this for multiple teams:

const teamExtended = [{
  name: 'My Team',
  players: [{
    player: 'Player 1',
    position: 'Forward'
  }, {
    player: 'Player 2',
    position: 'Midfield'
  }, {
    player: 'Player 3',
    position: 'Defender'
  }],
}, {
  name: 'Team 2',
  players: [{
    player: 'Player A',
    position: 'Forward'
  }, {
    player: 'Player B',
    position: 'Midfield'
  }, {
    player: 'Player C',
    position: 'Defender'
  }],
}]

function extractPlayers(team) {
  return team.players.map(info => {
    return {
      name: team.name,
      player: info.player,
      position: info.position
    }
  })
}

teamExtended.forEach(team => {
    let playerArray = extractPlayers(team);
  console.log(team.name, playerArray)
})

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

Utilizing an AngularJS service to communicate with a web API

Having trouble retrieving data from a web api and passing it back to a JavaScript file. I've tried using http://localhost:8584/api/Testing/5 to see if there are any results, but no luck so far. //This is the JavaScript controller that calls the serv ...

The Material UI read-only rating component fails to update even after the data has been successfully loaded

I have a rating component in my child component, and I am passing data from the parent component through props. However, there seems to be an issue with the MUI rating value not updating when the data is ready for viewing. It's interesting to note th ...

JavaScript event/Rails app encounters surprising outcome

I have encountered a strange bug in my JavaScript code. When I translate the page to another language by clicking on "English | Русский" using simple I18n translation, my menu buttons stop working until I reload the page. I suspect that the issue ...

Should I use Object.assign or define class properties?

Currently in the process of developing an angular application that interacts with the twitch API. The API returns data in various formats, some of which I need to parse and save into specific classes. My main concern is understanding the potential drawbac ...

Steps for inputting time as 00:00:00 in MUI's X DateTimePicker

React:18.2.0 mui/material: 5.10.5 date-fns: 2.29.3 date-io/date-fns: 2.16.0 formik: 2.2.9 I'm facing an issue with using DateTimePicker in my project. I am trying to enter time in the format Hour:Minute:Second, but currently, I can only input 00:00 f ...

Is there a way for me to confirm that I am receiving the 401 error when fetching data?

When using an async function to fetch data, how can one determine if a 401 error occurred during the data retrieval process? The code example is as follows: async function getBilling(url, id, date) { let header = { method: 'GE ...

Searching in Vue based on the selected option is only possible by the selected criteria and not by id, regardless of the

#1 Even if chosen, cannot search by id. The 'name' condition in the loop works well but I am unable to correctly search by id (returns nothing). #2 When selecting an option from the dropdown menu, it only displays until I start typing. I would l ...

Delaying Variable Assignment in Node.js until Callback Function Completes

I am currently working with Node.js, Express, MongoDB, and Mongoose in my project. One specific task involves fetching the largest id number of a document from the MongoDB database and passing it back to the program. To better organize my code, I moved thi ...

Transform a JSON string into an array of JSON objects using Java

Data is formatted as a String like this : String jsonData = "{"name":"A","age":23},{"name":"B","age":24}"; I am looking to transform the string above into an Array of Objects: Person[] persons; In which, persons[0].name => "A" persons[0].age => 23 .. ...

Node.js command prompt claims that 'react is non-existent'

Hello everyone! I'm excited to ask my first question on this site. I am relatively new to coding and currently learning React. Yesterday, I started working on my first project. Today, when I tried to initialize live-server and babel compiler for my J ...

trouble encountered when attempting to integrate typeahead functionality in AngularJS using jQuery

Greetings! I am brand new to using AngularJS and currently exploring the implementation of typeahead functionality. I decided to utilize an existing library by including the following script: <script src="lib/xyz/typeahead.bundle.js"></script> ...

Obtain the location of the image source from a text file within an HTML document

I need to create a slideshow displaying a sequence of images. The path to these images will be stored in a text file. How can I read the image paths from the text file? Currently, I have hardcoded code like the example below: <div class="mySlides fade" ...

How can I modify the color of a div when a validation error occurs?

I have recently completed a contact form with validation using the constraint validation api. Although the files are functioning as intended, I am curious if there is a method to make the error boxes turn red when an error occurs and white (or hidden) when ...

The Best Approach for Angular Google Maps Integration

I'm diving into Angular for the first time while working on a project that requires advanced mapping functionality like clustering, routing, road routing, paths, directions, polygons, events, drawing on maps, info windows, markers, etc. After some re ...

Basic Hover Effect in Javascript

Looking at this snippet of HTML: <div id="site-header-inner"> <div id="header-logo"> <?php echo wp_get_attachment_image(get_field('header_logo','options'),'full'); ?> </div> <div id= ...

How to retrieve a string from a regular expression in Javascript without [Object object] output

Within my code, there exists a parent form component and a child component used for auto-completing text input. The Parent component passes an array of objects named autoCompTxt, consisting of name and id fields, to the Child component. //Parent: const [ob ...

Updating subdata in an array using Reactjs handleChange

I am facing an issue with my handleChange function. While I can easily change data in the same directory without any problem, I'm struggling to update sub-data. I would like to find a clean solution for this without having to add extra functions withi ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

What is the best way to establish anchors for *ngFor elements in Angular 2 and beyond?

I have a component that displays items using *ngFor. My goal is to scroll down to the element with anchor #3. Here's the code snippet: @Component({ selector: 'my-app', template: ` <button (click)="scroll(3)">scroll 2</butt ...

Having issues with AJAX and button submit while trying to upload a file using Flask

I've been attempting to incorporate a file upload feature (specifically a .csv file) using bootstrap, and then submit it by clicking on a button. I've experimented with various methods to implement the file upload functionality, but haven't ...