What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows:

let myObject = {
  internalValue:{city:"Paris", country:"France", pinCode:12345}, 
  originalValue:{city:"Nantes", country:"France", pinCode:34567}, 
  score:{city:10, country:100, pinCode:45}
};

The desired output array should look like this:

[
  [
    {detail:"Paris", label:"internalValue"},
    {detail:"Nantes", label:"originalValue"},
    {detail:10, label:"score"}
  ],
  [
    {detail:"France", label:"internalValue"},
    {detail:"France", label:"originalValue"},
    {detail:100, label:"score"}
  ],
  [
    {detail:12345, label:"internalValue"},
    {detail:34567, label:"originalValue"},
    {detail:45, label:"score"}
  ]
]

Currently, the code I have written for this transformation is as follows:

let tableData:any;
tableData = _.transform(myObject, result, value, key)=>{
  let retValue:any;
  _.forIn(value, (v,k)=> {
    let tempArr:Array<any>;
    let tempObj:any = {};
    tempObj.detail= v;
    tempObj.label=key;
    tempArr.push(tempObj);
    retValue.push(tempArr);
  })
  result = [...retValue];
  return result;
},[]);

I seem to be stuck when it comes to moving on to the next set of loops.

Answer №1

There's no need for Lodash in this scenario. One can achieve the desired outcome by utilizing the Object.keys and Object.values methods to loop through the object properties.

To begin with, extract the necessary keys (city, country, pinCode) from the first object value and iterate over them. Here is an illustration:

let myObject = {
  internalValue:{city:"Paris", country:"France", pinCode:12345}, 
  originalValue:{city:"Nantes", country:"France", pinCode:34567}, 
  score:{city:10, country:100, pinCode:45}
};

let keys = Object.keys(myObject);
let values = Object.values(myObject);

let result = Object.keys(values[0]).map((_, i) => {
  return keys.map(key => {
    return {detail: myObject[key][Object.keys(values[0])[i]], label: key};
  });
});

console.log(result);

Answer №2

Start by defining an array of keys that you want to extract (referred as 'fields' in this instance). Utilize the Object.entries() method on the original object to retrieve an array containing pairs of [key, value] (referred as 'entries' here). Proceed to map both the 'fields' and 'entries' arrays in order to generate a new array for each specified field:

const fields = ['city', 'country', 'pinCode'];

const extractFields = obj => {
  const entries = Object.entries(obj);

  return fields.map(field => 
    entries.map(([label, val]) => ({
      detail: val[field],
      label
    }))
  );
};

const myObject = {
  internalValue:{city:"Paris", country:"France", pinCode:12345}, 
  originalValue:{city:"Nantes", country:"France", pinCode:34567}, 
  score:{city:10, country:100, pinCode:45}
};

const extractedResult = extractFields(myObject);

console.log(extractedResult);

Answer №3

Check out this example showcasing how lodash can be used:

let myData = {
  innerData:{city:"Tokyo", country:"Japan", pinCode:54321}, 
  originalData:{city:"Kyoto", country:"Japan", pinCode:76543}, 
  point:{city:15, country:50, pinCode:75}
};

const extractDetails = (data, keys = _.chain(data).values().map(_.keys).first().value()) => {
   // OR keys = Object.keys(Object.values(data)[0])

    return keys.map(key => {
        return _.chain(data)
        .mapValues(key)
        .map((detail, label) => ({ detail, label }))
        .value();
    });
};

const specifics = extractDetails(myData, ["city", "country", "pinCode"]);
console.log("specifics", specifics);

const general = extractDetails(myData);
console.log("general", general);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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

In Firefox, using the new Date function within a string does not function as expected

Why does the last log in the code snippet below not work in Firefox? (function() { String.prototype.toDate = function() { return new Date(this); }; console.log(Date.parse("2012-01-31")); console.log(new Date("2012-01-31")); c ...

unable to use 'await' keyword to delay the code execution until a function finishes

I'm encountering an issue where I need to wait for the result of a local function before proceeding further. Here is the code for the local function: var Messagehome = (req, res) => { user.find().exec(async (err, user) => { if (err) ret ...

Powering up your React components with MDX, Storybook, and Typescript!

Currently, I am attempting to incorporate MDX markup into the creation of live documentation for my storybook. However, upon running the storybook, an error is occurring: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C ...

Express JS encountering Firebase Google Sign-In glitch

Whenever a user clicks a button on the HTML page, this function is triggered. The function resides in auth.js and it is called from the server.js page. auth.js const firebase = require("firebase"); static googleSignIn(req,res){ firebase.aut ...

Ways to retrieve parameters in getStaticPaths function?

I'm currently working on a Next.js app with Contentful as the CMS. The file structure relevant to my question is: pages -[category] -[slug].js My goal is to access the category value when a user visits category/slug. Currently, I have the category ...

What is preventing me from using AJAX to input data into sqlite?

Implementing a local save feature in my Web App is proving to be quite challenging. Every time I attempt to send data in any form, I consistently encounter the following error: A builtins.TypeError occurs, followed by a stack trace in /SaveFile and jquery ...

Running various IT blocks within a Protractor loop to enhance web testing

After logging in to a web page, we need to use a for loop to perform multiple tests on the page. The ideal test scenario involves a table with buttons on each row that leads to another page where data needs to be validated. Currently, all expectations and ...

Adding an id to a ul tag using JavaScript

I am trying to dynamically add an ID called "myMenu" using JavaScript to a ul element for a search filter. Unfortunately, I am unable to directly access the ul tag to change it, so I need to do it via JavaScript. As I am new to JavaScript, I am looking t ...

Escape from an iframe with the help of a buster

My website is being targeted by a code that prevents it from breaking out of an iframe. Despite trying different frame breaker scripts, I have not been successful in resolving this issue. Any assistance would be greatly appreciated. Thanks! Buster: func ...

Transforming text into numbers from JSON response with *ngFor in Angular 6

I'm currently attempting to convert certain strings from a JSON response into numbers. For instance, I need to change the zipcode value from "92998-3874" to 92998-3874. While doing this, I came across a helpful resource on Stack Overflow. However, I s ...

What is the most effective way to display a card with varying values depending on the user's input in a form?

For a while now, I've been grappling with a particular challenge. In my project, I am utilizing multiple states to display values within a card after they are entered into a form. The first state captures the values and modifies the initial state, whi ...

I need to extract information from the database and save all entries from the form in order to send them to myself. This includes calculating the real-time multiplication of weight and pieces

For a project, I need to gather contact data from the client, and then populate a MySQL database with the information to create new rows in a table. There's an additional requirement where I have to calculate the total weight of element pieces multip ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

Having trouble retrieving an object property in HTML or TypeScript within an Angular framework?

export class ComponentOne { array_all_items: Array<{ page_details: any }> = []; array_page_details: Array<{ identifier: number, title: string }> = []; initial_item: Array<{ identifier: number, title: string }> = [ { ...

Ensuring the Persistence of Column State in Material-UI DataGrid/DataGridPro when Adjusting Visibility Using Column Toolbar

We have integrated MUI DataGrid into our React project. Currently, I am exploring options to save the state of columns after toggling their visibility using the DataGrid toolbar column menu. After each re-render, the column setup returns to its default st ...

Is there a way to deactivate or dim a specific hour in an HTML time form?

I am currently facing a challenge with my booking form. I need to find a way to grey-out or disable the hours/times that have already been booked by previous customers. This will help ensure that the next person can select a different time slot. However, I ...

Is it possible to animate multiple SVGs on a webpage with just the click of a button?

Is there a way to trigger the animation in the SVG each time a next/prev button is clicked while navigating through a carousel where the same SVG is repeated multiple times? The carousel is built using PHP and a while loop. jQuery(document).ready(function ...

Displaying the chosen array in a Material UI Table within a React application does not show the desired checkboxes

After days of hard work and research, I finally figured out how to achieve what I needed. In my React App, I have a Material UI table that I want to load with pre-rendered checks in the DOM based on entries in a selected array. The selected array contains ...

Is it possible to adjust the timezone settings on my GraphQL timestamp data?

I've come across a lot of helpful information regarding the usage of Date() and timezones, but something seems to be off. In my GraphQL setup (sourcing from Sanity), I have configured it to use formatString in this manner: export default function Minu ...

HTML5 database error: Uncaught TypeError due to illegal invocation

When I test the code below in Chrome, I encounter an error: var db = openDatabase('foo', 1, 'foo', 1111); var sql = function(callback){ db.transaction(function(tx){ callback(tx.executeSql); }); }; sql(function(query){ ...