Combining sub-array into main property

After organizing my data, I am looking to convert it into a flat structure

data = [
   {
      "Name":"Gorba Technology",
      "Product":"Dell",
      "City":[
         "Delhi",
         "Mumbai"
      ]
   },
   {
      "Name":"Suvidha Computer",
      "Product":"Lenovo",
      "City":[
         "Deoghar"
      ]
   },
   {
      "Name":"Sara Laptop",
      "Product":"Dell",
      "City":[
         "Noida",
         "Delhi"
      ]
   }
]

The desired output should look like this:

[{"Name":"Gorba Technology","City":"Delhi"},
{"Name":"Gorba Technology","City":"Mumbai"},
{"Name":"Suvidha Computer","City":"Deoghar"},
{"Name":"Sara Laptop","City":"Rajasthan"}
{"Name":"Sara Laptop","City":"Delhi"}]

I attempted the following approach but was unsuccessful:

var result = data.map(({Name, City}) => City.map(item => {Name, item}));

In an attempt to achieve the desired output without using flatMap, I encountered lint errors when trying to implement flatMap.

Answer №1

To optimize your code, consider using the reduce function instead of map

data.reduce((acc, {Name, City}) => {
  City.each((city) => {
    acc.push({Name, City: city});
  });
  return acc;
}, []);

Answer №2

map() function always produces an output array of the same length as the input array, which may not meet your specific requirements.

An alternative approach could involve utilizing reduce() and forEach().

In the provided example JSON data, there is a destructure operation where multiple objects are created for each city associated with the same company name:

const data = [
   {
      "Name":"Gorba Technology",
      "Product":"Dell",
      "City":[
         "Delhi",
         "Mumbai"
      ]
   },
   {
      "Name":"Suvidha Computer",
      "Product":"Lenovo",
      "City":[
         "Deoghar"
      ]
   },
   {
      "Name":"Sara Laptop",
      "Product":"Dell",
      "City":[
         "Noida",
         "Delhi"
      ]
   }
]

var result = data.reduce((acc,{Name,City}) => { 
  const items = [];
  City.forEach(city=> {
  items.push({Name , City : city});
  });
  return [...acc,...items];
},[]);

console.log(result);

Answer №3

const info = [
   {
      "Name":"Tech Pros",
      "Product":"HP",
      "City":[
         "New York",
         "Los Angeles"
      ]
   },
   {
      "Name":"PC World",
      "Product":"Asus",
      "City":[
         "Chicago"
      ]
   },
   {
      "Name":"Electro Gadgets",
      "Product":"Apple",
      "City":[
         "San Francisco",
         "Seattle"
      ]
   }
];

const updatedInfo = [];

info.forEach(item => {
  if (item?.City?.length) {
    item.City.forEach(city => {
      const newObj = {...item, City: city};
      updatedInfo.push(newObj);
    })
  }
});

console.log(updatedInfo);

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

Strange problem encountered when transferring data to and from API using Typescript and Prisma

I'm encountering a strange issue that I can't quite pinpoint. It could be related to mysql, prisma, typescript, or nextjs. I created the following model to display all product categories and add them to the database. Prisma Model: model Product ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

Anchor text in Primeng using p-radioButton

Can the text of a radio button be transformed into an anchor link? Visit this link for more information. For example, Option 1 could be turned into a clickable link that opens a new browser window with relevant content. Keep in mind that trying to place ...

Creating an object type that accommodates the properties of all union type objects, while the values are intersections, involves a unique approach

How can I create a unified object type from multiple object unions, containing all properties but with intersecting values? For example, I want to transform the type { foo: 1 } | { foo: 2; bar: 3 } | { foo: 7; bar: 8 } into the type {foo: 1 | 2 | 7; bar: ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

unable to retrieve getters within the store module

This is the explanation of my store module. // rest defined earlier const _GETTERS = { getName: state => { return state.current.name; }, getLastName: state => { return state.current.lastName; }, getFullName: (state, getters) => ...

If I don't utilize dependency injection in Angular, it prompts me for arguments

Attempting to implement a service like this but encountering some issues translateService = new TranslateService(); An error message pops up stating that there are 9 missing arguments. However, when I modify it to look like this constructor(private trans ...

ReactJS Error: The property 'hubConnection' is not defined on type 'JQueryStatic'

I am currently working with the Signalr library in React, but I keep encountering the following error: Property 'hubConnection' does not exist on type 'JQueryStatic'. Is there a solution to this issue? declare var window : any; import ...

How can we ensure a generic async function with a return type that is also generic in Typescript?

I'm currently working on a function that retries an async function multiple times before rejecting. I want to make sure the typescript typings of the retry function are maintained and also ensure that the passed function is of type PromiseLike. Creat ...

The return type of Array.find is accurate, however, it contains an error

Trying to find a way to indicate the expected return type of Array.find() in TypeScript, I encountered an incompatibility warning. View code in playground class A { "type"="A" t: string; #a = 0 constructor(t: string) { ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

Enforcing strict type checking in TypeScript with noImplicitAny for undeclared variables

Why doesn't TypeScript give a warning about implicit any when creating a variable whose type changes through multiple assignments? // TypeScript allows this without any warnings let variable; variable = "string"; variable = 5; // But it won ...

When hosting on render.com, the session data is not retained when redirecting to other routes

My login API checks if the user has a saved cookie in MongoDB and saves the value into req.session using the req.session.save() method. Afterward, it redirects to another route to create a response and send the client session data to be used. This function ...

Implementing the strictNullCheck flag with msbuild

Can strict null checks be enabled when compiling using msbuild? I see in the documentation that the compiler option is --strictNullChecks, but I couldn't find any specific entry for it on the msbuild config page. Is there a method to activate this f ...

Angular Owl Carousel doesn't slide horizontally, it slides vertically

Within my Angular project, I incorporated an Owl Carousel into the home-component.html file. Here is a snippet of the code: <section> <div class="container"> <h1 class="products-title">New Arrivals</h1> ...

How can you initialize Boostrap components or Materialize css in Angular 5 without using any external libraries?

I am a beginner exploring the world of Typescript and Angular. I am curious about how to initialize Bootstrap elements in an Angular-friendly manner without using the ngx-Bootstrap wrapper. For instance, if I wish to initiate a Bootstrap carousel. As per ...

React Redux not properly handling text input updates when onChange event is triggered

I have come across similar inquiries, but they haven't provided the solution I need. Currently, I am working on a React project where I am integrating redux. This is how my index.js looks: import React from "react"; import ReactDOM from "react-dom"; ...

Import reactjs modules without the need for Browserify, Webpack, or Babel

I am attempting to set up a TypeScript HTML application in Visual Studio. My goal is to incorporate reactjs v0.14.7 without relying on tools like Browserify. But, how can I utilize the react-dom module in this scenario? Let's set aside TypeScript fo ...

What is the best way to include UMD in a browser using the <script type="module"> tag, while also importing

Is there a way to transpile TypeScript code and import it directly into the browser without using Webpack? I'm running into some issues with node_modules in my code which is making this process more complex. I attempted to import it as a module: < ...