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

Can you provide me the steps to delete the title attribute from images in Wordpress?

My client has expressed dissatisfaction with the tooltip that appears when hovering over images in certain browsers, particularly Safari. This tooltip displays the title attribute within the img tag, which is a requirement enforced by Wordpress. Even if w ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...

What is the method for configuring the URL of an ajax request to open in a separate window?

I am currently working on an ajax call where I need to open a URL in a new tab or window. Since I'm still learning about ajax, I would greatly appreciate any help and explanation that you can provide. Below is the code snippet: $.ajax({ url: &apo ...

What could be causing the error where axios.get is not functioning properly?

Recently, I embarked on a journey to familiarize myself with working with packages and npm. My first step was to import axios for a simple http request. Initially, I set up the project using npm init successfully. However, I encountered my first roadbloc ...

Drawing images on a Canvas using specified coordinates: A step-by-step guide

https://i.stack.imgur.com/YkibI.jpg I've been trying to position images on specific coordinates, but I'm having trouble getting the shapes and angles right. Currently, only the top left corner is matching correctly. var _width, _height; var im ...

I could really use some assistance with this script I'm working on that involves using ($

Using Ajax for Form Submission: $.ajax({ url: 'process.php', type: 'post', data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(), dataType: 'json', success: func ...

How does the 'this' variable function when it comes to models in embedded documents?

Being relatively new to node.js and sails, I find it quite easy to work with and enjoy it :) Currently, I am using the sails Framework version 0.10rc3 with MongoDB and sails-mongo. I understand that the contributors of waterline do not particularly like e ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

Trouble with basic JavaScript functionality in a React component

Here is a unique component code snippet: import React, {Component} from 'react'; import 'D:/School/Alta/interactiveweb/src/webapp/src/App.css' class Chat extends Component { test() { alert(); } render() { return <nav ...

Trouble passing data back to main window after clicking ng-modal button in Angular

While working on the NG-Model window, I encountered an issue with my code. Initially, everything was functioning as expected when applied to a select element that is a radio button. However, when I changed the code to use the Click method for a button, it ...

Importing ReactDOM alone does not result in the rendering of anything

Having just started delving into the world of React, I've been grappling with getting a React app up and running. Despite my efforts, all I can manage to see is a blank page. Can anyone offer some assistance? HTML Markup (index.html) <html> & ...

Access the extended controller and call the core controller function without directly interacting with the core controller

i have a core controller that contains an array called vm.validationTypes with only 2 objects. I need to add 3 or 4 more objects to this array. to achieve this, i created another controller by extending the core controller: // CustomValidation angular.m ...

URL for image preview on Amazon S3

Is there a way to retrieve preview images from my Amazon S3 image storage instead of always fetching the full-sized 5MB images? If necessary, I would then be able to request the normal image. ...

Utilizing node-json2html, generate individual HTML tables for each record

I need assistance in consolidating my JSON data into a single HTML table, instead of generating separate tables for each record through my current transformation process. var data=[{"name":"aa","mid":"12345","user":"a123","password":"a@123"},{"name":"bb" ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

Tips for customizing the appearance of a mat-select chosen item?

Is there a way to modify the color of the selected option text in a mat-select component within an Angular 15 project? .html <mat-form-field> <mat-label>From</mat-label> <mat-select panelClass="mat-select-red"> ...

It is not possible to execute an injectable function using a service instance, as the parameter value consistently stays as null

I am utilizing an angular web app that relies on access tokens that have the potential to expire. When they do expire, a 401 status response is sent back to the app, triggering processing by a retryWhen operator. The logic for initiating a token refresh AP ...

Tips for distinguishing a mapped type using Pick from the original type when every property is optional

I am working with a custom type called ColumnSetting, which is a subset of another type called Column. The original Column type has most properties listed as optional: type ColumnSetting = Pick<Column, 'colId' | 'width' | 'sort ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

Eliminating unique phrases from text fields or content sections with the help of jQuery or JavaScript

I'm currently working on a PHP website and have been tasked with the responsibility of removing certain special strings such as phone numbers, email addresses, Facebook addresses, etc. from a textarea that users input data into. My goal is to be able ...