List of nested objects converted into a flat array of objects

Looking to transform a data structure from an

array of objects containing objects
to an objects in array setup using JavaScript/Typescript.

Input:

[
  {
    "a": "Content A",
    "b": 
    {
      "1": "Content 1",
      "2": "Content 2"
    }
  },
  {
    "y": "Content Y",
    "x": 
    {
      "3": "Content 3",
      "4": "Content 4"
    }
  },

]

Expected output

[
  {a: "Content A", b: "Content 1"}, 
  {a: "Content A", b: "Content 2"},
  {y: "Content Y", x: "Content 3"},
  {y: "Content Y", x: "Content 4"}
]

Providing solutions in both TypeScript and JavaScript would be greatly appreciated!

Answer №1

Here is the solution you can try:

const all = [
    {
      "a": "Content A",
      "b": 
      {
        "1": "Content 1",
        "2": "Content 2"
      }
    },
    {
      "y": "Content Y",
      "x": 
      {
        "3": "Content 3",
        "4": "Content 4"
      }
    },
];
console.log(all.reduce((prev, el) =>{
    let curr = Object.entries(el);
let k1 = curr[0][0];
let k2 = curr[1][0];
    Object.entries(curr[1][1]).forEach((o => {
        
        let obj ={}
        obj[k1] = curr[0][1];
        obj[k2] = o[1];
        prev.push(obj);
    }))
    return prev;
},[]))

Answer №2

Utilize the flatMap method along with Object.entries

const result = (arr) =>
  arr.flatMap((item) => {
    const [key1, str] = Object.entries(item).find(
      ([, val]) => typeof val === "string"
    );
    const [key2, obj] = Object.entries(item).find(
      ([, val]) => typeof val === "object"
    );
    return Object.values(obj).map((value) => ({ [key1]: str, [key2]: value }));
  });

const information = [
  {
    a: "Content A",
    b: {
      "1": "Content 1",
      "2": "Content 2",
    },
  },
  {
    y: "Content Y",
    x: {
      "3": "Content 3",
      "4": "Content 4",
    },
  },
];

console.log(result(information))

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

Issues with appending characters to char*[] array

I am currently working on creating a TicTacToe game for my class, and I'm encountering problems with two characters that I have designated for X and O. The assignment requires us to use certain code, so I cannot simply use a standard array. Whenever I ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

Data not being retrieved by HTTP GET request

I encountered an issue with my API where I made three Get requests using the same function but different URLs to differentiate between them. However, even though the provider returns the data in steps, the page response function does not receive it and sho ...

Strange activities observed during the management of state in react hooks, where the splice() function ends up eliminating the

My current setup involves maintaining a state to handle the addition of new JSX elements: const [display, setDisplay] = useState<IDisplay>({ BookingFormDropDown: [], } ); I have a function in onClick() which adds an elem ...

Troubleshooting: JQuery dropdown selection not updating image display

I am trying to create a select menu that changes the car image when a user selects a different model, but for some reason it is not working. Here is what I have tried: <h2 class="model">A6 <img src="images/3.jpg" id="image" width="544" height="2 ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...

Gauging Screen Size: A Comparison between Media Queries and JavaScript for Adjusting Div Position

I am currently facing an issue with the banner on my website. It contains a slider and has a position set to absolute. The problem arises when viewing it on smaller screens, as only the left side of the wide banner is visible. Initially, I tried using med ...

What are the steps to resolve TypeScript errors in OpenLayers version 6.6.1?

Since updating to OpenLayers 6.6.1, I have been bombarded with numerous typescript errors related to generics. For example... import olLayerVector from 'ol/layer/Vector'; import olFeature from 'ol/Feature'; public static highlightOver ...

A guide to using jqGrid: Retrieve the value of a particular cell by double clicking on a row

Is there a way to implement a feature where users can double click on any part of a row and have it open a new HTML page based on the specific content in a cell? For example, I have a table with different counties in New York listed in separate rows: Coun ...

Utilizing Data Binding in D3.js

Why is the text "Hello" not appearing five times on the page as expected? index.html <html> <head> <title>Data Binding</title> </head> <body> <h1>D3.js</h1> <script src="https://d3js.o ...

Retrieve deeply nested information without excessive nested looping structures

I am facing a challenge with processing a large dataset that requires accessing nested values for a database insert using a "deep loop". Although my current code successfully achieves this, it is slow and often times out before completing the data process ...

What strategies can I use to preserve type narrowing when utilizing the Array.find method?

Within the code snippet below, I am encountering a typescript compilation error specifically in the Array.find method. Despite checking that `context.params.id` is not `undefined`, my type seems to lose its narrowing. I'm puzzled as to why this type ...

Map several keys to a single value within an array

$lang = array( 'thank you'=>'You are welcome', 'thanks'=>'You are welcome', 'thank ya'=>'You are welcome' ); It seems redundant to write multiple keys for the ...

Find the location in a node.js script where a promise was rejected

Recently, I encountered a code snippet from an npm package that has been causing me some trouble. The issue is that I'm having difficulty in pinpointing where the rejected promise is being created or rejected within node.js. const someHiddenEvil = fu ...

Neglecting the inclusion of a property when verifying for empty properties

In the code snippet below, I have implemented a method to check for empty properties and return true if any property is empty. However, I am looking for a way to exclude certain properties from this check. Specifically, I do not want to include generalReal ...

What is the process for logging out when a different user signs in using Firebase authentication in a React Native application?

I am new to React Native and facing challenges with managing authentication state in my application. Currently, I am using Redux but have not yet implemented persistence for user login. I have incorporated Firebase authentication. Essentially, I would li ...

No need to conceal content when switching to another tab if the tab is set to stay in place

My current setup involves using material UI and react-sticky, which has been functioning well. However, I have encountered an issue that I am seeking help with. Here is a link to what I have tried so far. Below are the steps to reproduce this issue: S ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

I am experiencing an issue where Discord.js is unable to assign a role to a new member upon joining my server

I'm trying to set up my bot to automatically assign a specific role to new members when they join the server. However, I keep encountering a strange error that I can't seem to figure out. Here is the code snippet in question: const { GuildMember ...

Customizing number input types in Angular 2 - the perfect solution

Attempting to incorporate a time picker using HTML5 input type number in Angular2. The code snippet below illustrates the setup: <input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12"> <input type="number" ...