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

Using ng-init to pass a JSON object

I'm attempting to pass a JSON Object to my application using ng-init and the stringify method, but I am encountering an error. Instead of working as expected, I am getting a Lexer error. Lexer Error: Unexpected next character at columns 8-8 [#] in ex ...

Guide to utilizing JavaScript for a basic gaming experience

Looking to incorporate multiple divs that will vanish upon being clicked, while also increasing the score by 1 through javascript. Any suggestions on how to accomplish this? ...

Tips for managing blur events to execute personalized logic within Formik

I am currently delving into the world of React/Next.js, Formik, and Yup. My goal is to make an API call to the database upon blurring out of an input field. This call will fetch some data, perform database-level validation, and populate the next input fiel ...

Meteor twilio SMS feature not functioning properly

I'm currently using the Twilio node for sending SMS, but I've encountered an error: sendSms is not defined Within my server folder, here is the Twilio file I have: import twilio from "twilio"; sms = { accountSid: "xxxxxxxxxxxxxxxxxxxxxxx ...

Retrieve the child grid's data source in Kendo using Angular

I am currently working with a master detail grid in Kendo Grid and using the Angular version of the Kendo Grid. One interesting feature I have added is a custom button for adding a new record in each row of the grid. When this button is clicked, a new rec ...

Retrieve the identifier of the higher-order block when it is clicked

When I have a parent block with a nested child block inside of it, I expect to retrieve the id of the parent when clicked. However, the event target seems to be the child element instead. Is there a way for JavaScript to recognize the parent as the event ...

Exploring the Depths of Google Chrome: Unleashing the Power of

While a similar question has been posed previously, I am encountering difficulties debugging Javascript in Google Chrome. When I navigate to Page > Developer, the "Debug Javascript" function (Ctrl+Shift+L) is not active. Even trying Alt + ` does not se ...

Using Selenium and Python to showcase the source of an image within an iframe

My goal is to automatically download an image from shapeNet using Python and selenium. I have made progress, but I am stuck on the final step. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.s ...

Acknowledging client after client to server POST request has been successfully processed in Node.JS

I've been working on responding to client-side requests with Node.JS. While searching, I came across a helpful article on calling functions on the server from client-side JavaScript in Node JS. However, I'm having trouble implementing it in my pr ...

Access the HTML file from a different directory

I have a directory called "myWebsite". Within this directory, there is a file named "index.html" and another subdirectory named "other". Inside the "other" directory, there are CSS files, JS files, and "page2.ht ...

Encountering issues with loading Angular formControl

I've been going through an Angular tutorial on forms, which you can check out here. In my 'datasources.component.html' file, I have the following code: <form [formGroup]="queryForm"> <label>Query: <input type="text" formCont ...

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...

Identifying periods of inactivity using an embedded iframe

I have developed a website that showcases a three.js model within an iframe. My goal is to redirect users back to the homepage (index.html) after they have been inactive for a specified amount of time. While I have managed to achieve this using JavaScript, ...

Determine the vertical dimension of an element through a JavaScript event listener

I've been working on creating an Apple-style image sequence scroller from a codepen demo. Here's the link to the original: https://codepen.io/jasprit-singh/pen/LYxzQjB My goal is to modify the JavaScript so that the scroll height is based on a p ...

Load grid data only when the tab is clicked in ExtJS

Our app features a dynamic grid loaded with multiple tabs, each containing one or more grids. The issue currently is that when the application loads, it automatically calls all the URLs instead of waiting for the user to click on a tab. We want to optimi ...

Tips for resolving issues with storing data in a text box that is constantly being added to

Can someone please assist me with this issue I'm facing? I am using isset to check if the index is defined, but it stores 0 instead of saving the value of the textbox. How should I tackle this problem? If I don't check if the index is defined and ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

Jenkins process encounters issues with sed execution

I am currently facing an issue where a script that runs successfully locally encounters difficulties during our Jenkins build process, specifically with the 'sed' command. Below is the code snippet I am using. I have double-checked the file path ...

What is the process of emphasizing a WebElement in WebdriverIO?

Is there a way to highlight web elements that need to be interacted with or asserted in webdriverIO? Or is there a JavaScript code similar to the javascript executor in Selenium that can be used for this purpose? ...

What sets apart a space after the ampersand from no space in Material UI?

Could you clarify the difference between using a space after the ampersand compared to not having a space? For example: Why is there a space after the ampersand in & label.Mui-focused but no space in &.Mui-focused fieldset? const WhiteBorderTextF ...