Convert items to an array utilizing lodash

I need assistance converting an object into an array format. Here is the input object:

{
  "index": {
    "0": 40,
    "1": 242
  },
  "TID": {
    "0": "11",
    "1": "22"
  },
  "DepartureCity": {
    "0": "MCI",
    "1": "CVG"
  },
  "ArrivalCity": {
    "0": "SFB",
    "1": "LAS"
  },
  "Price": {
    "0": 90,
    "1": 98
  }
}

The desired output should look like this:

[
  {
    "index": 40,
    "TID": "11",
    "DepartureCity": "MCI",
    "ArrivalCity": "SFB",
    "Price": 90
  },
  {
    "index": 242,
    "TID": "22",
    "DepartureCity": "CVG",
    "ArrivalCity": "LAS",
    "Price": 98
  }
]

I attempted to use for loops, but it became quite complicated. Any help on simplifying this process would be greatly appreciated.

Answer №1

Check out this innovative solution using the lodash library

_.merge([], ..._.map(obj, (v, k) => _.mapValues(v, ev=> ({[k]:ev}))))

let inputObj = {
  "index": {
    "0": 40,
    "1": 242
  },
  "TID": {
    "0": "11",
    "1": "22"
  },
  "DepartureCity": {
    "0": "MCI",
    "1": "CVG"
  },
  "ArrivalCity": {
    "0": "SFB",
    "1": "LAS"
  },
  "Price": {
    "0": 90,
    "1": 98
  }
};

let res = _.merge([], ..._.map(inputObj, (v, k) => _.mapValues(v, ev=> ({[k] :ev}))));

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Answer №2

Utilize the reduce method to transform the entries into an array of objects by iterating through each value of the inner objects:

const data={"id":{"0":30,"1":215},"RoomType":{"0":"Standard","1":"Suite"},"Occupancy":{"0":2,"1":4},"Price":{"0":120,"1":250}}

const result = Object.entries(data).reduce((acc, [key, obj]) => {
  Object.values(obj).forEach((value, index) => {
    if (!acc[index]) acc[index] = {};
    acc[index][key] = value;
  });
  return acc;
}, []);
console.log(result);

Answer №3

To optimize your code, try using Object.keys along with the method reduce

let data = { "key": { "0": 40, "1": 242 }, "ID": { "0": "11", "1": "22" }, "StartCity": { "0": "MCI", "1": "CVG" }, "DestinationCity": { "0": "SFB", "1": "LAS" }, "Cost": { "0": 90, "1": 98 } }

result = Object.keys(data['key']).map(function(index){
  return Object.keys(data).reduce(function(obj, item){
    obj[item] = data[item][index];
    return obj;
  }, {});
});
console.log(result);

Answer №4

One way to organize the inner values is by mapping them to their corresponding index.

var data = { index: { 0: 40, 1: 242 }, TID: { 0: "11", 1: "22" }, DepartureCity: { 0: "MCI", 1: "CVG" }, ArrivalCity: { 0: "SFB", 1: "LAS" }, Price: { 0: 90, 1: 98 } },
    result = Object
        .entries(data)
        .reduce(
            (r, [k, o]) => Object
                .entries(o)
                .map(([i, v]) => Object.assign(r[i] || {}, { [k]: v })),
            []
        );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №5

Utilizing the power of lodash, you can easily achieve the desired result by employing the _.reduce() and _.forEach() methods in the following manner:

const outcome = _.reduce(Object.entries(object), function(a, [key, obj]){
  _.forEach(Object.values(obj), function(val, i){
    if (!a[i]) a[i] = {};
    a[i][key] = val;
  });
  return a;
}, []);

Check out this demonstration:

const object = {
  "index": {
    "0": 40,
    "1": 242
  },
  "TID": {
    "0": "11",
    "1": "22"
  },
  "DepartureCity": {
    "0": "MCI",
    "1": "CVG"
  },
  "ArrivalCity": {
    "0": "SFB",
    "1": "LAS"
  },
  "Price": {
    "0": 90,
    "1": 98
  }
};

const outcome = _.reduce(Object.entries(object), function(a, [key, obj]){
  _.forEach(Object.values(obj), function(val, i){
    if (!a[i]) a[i] = {};
    a[i][key] = val;
  });
  return a;
}, []);

console.log(outcome);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.js"></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

Validate if a string in JQuery contains a specific substring

How can I determine if one string contains another string? var str1 = "ABCDEFGHIJKLMNOP"; var str2 = "DEFG"; What function should I utilize to check if the string str1 includes the string str2? ...

Try utilizing a variety of background hues for uib progressbars

Looking to incorporate the ui-bootstrap progressbar into my template in two different colors, background included. My initial idea was to stack two progress bars on top of each other, but it ended up looking too obvious and messy, especially in the corner ...

Marionette's Take on the Undead: Zombie Perspectives

Error in JS Console: Uncaught ViewDestroyedError: View (cid: "view351") has already been destroyed and cannot be used. backbone.marionette.js?body=1:1715 Code Snippet: initialize: (options) -> HWAs = @model.get('homework_assignments') @ ...

What is the best method for extracting html-string from html-string across different browsers?

Works perfectly in Chrome and FF, but encountering issues with Safari. var content = '<div><span><p>Can you catch me?</p></span></div>'; content = $.parseXML(content); var span = $(content).find('span&apo ...

Error: We are facing an issue with new.mongoose.Schema as it is not functioning properly and

I am experiencing an issue with my product.js file. It keeps throwing an error about an unidentified identifier, and whenever I try to fix one problem, another one pops up. I have been struggling to locate the root cause of this error. ...

Experiencing a problem with value formatting while attempting to implement tremor for charts in React with Next.js version 13

import { getAuthSession } from "@/lib/auth"; import { db } from "@/lib/db"; import { Card, LineChart, Text, Title } from "@tremor/react"; import Linechart from "./LineChart"; const dollarFormatter = (value: number) ...

Enhancing the session helper in Silex with additional values

Hey there, I'm currently working on a basic shopping cart using an MVC framework called Silex. However, I've run into a JavaScript/AJAX issue that I could use some help with. My problem arises when trying to add a product to the basket. The issue ...

The div smoothly descended from the top of the page to the center under the control of jQuery

I am trying to implement a feature where a div slides down from the top of the page to the center when a button is clicked. However, my current code seems to be causing the div to slide from the bottom instead of the top. Ideally, I want the div to slide ...

Connecting an admin dashboard to a MERN e-commerce application: A step-by-step guide

In the process of developing an e-commerce platform, I find myself using React.js for the frontend and Node.js/Express.js for the backend. My current challenge lies in creating a seamless dashboard to manage items within the app. One possible solution wo ...

React App folders are not being properly installed through NPX

Encountering an error message while attempting to use npx create-react-app Husna@LAPTOP-LPCC954R MINGW64 ~/Desktop/React GitHib Project (master) $ npx create-react-app github2020 Creating a new React app in C:\Users\Husna\Desktop\Reac ...

The Javascript function is malfunctioning, unable to assign the 'onclick' property to null

Here's the code snippet I'm working with: var exit = document.getElementById("exit"); exit.onclick = function() { "use strict"; document.getElementById("fadedDiv").style.display = "none" ; }; However, when I check the console, it shows ...

Unable to sort the list items when utilizing the load() function

I have multiple li elements within a ul and I am using the following code to sort them in ascending order based on the data-percentage attribute: $(function() { $(".alll li").sort(sort_li).appendTo('.alll'); function sort_li(a, b) { re ...

How can I retrieve the path to a specific subnode using Javascript/JSON?

What is the best way to obtain a JSON path that leads to a specific child node within an object? For example: var data = { key1: { children: { key2:'value', key3:'value', key4: { ... } ...

What are some ways I can efficiently load large background images on my website, either through lazy loading or pre

Just dipping my toes into the world of javascript. I'm currently tackling the challenge of lazy loading some large background images on my website. My goal is to have a "loading" gif displayed while the image is being loaded, similar to how it works ...

How can I make the input box TextField in Material UI with React expand to full width when selected?

I am currently customizing a Material UI form where the input box (Text Field) starts off at a width of 200px. My goal is to have the input box expand to 100% width only when it is selected or clicked on. ... <FormGroup sx={{ maxWidth: "200px" ...

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

Encountering a TypeError while trying to import grapesjs into a nextjs project, specifically receiving the error: "Cannot read properties of null (reading 'querySelector')

I encountered an issue while trying to integrate grapesjs into a nextjs project. The error I received was TypeError: Cannot read properties of null (reading 'querySelector') It appears that grapesjs is looking for the "#gjs" container by its id ...

Step-by-step guide for properly transferring PHP MySQL data to ChartJs

I am looking to create bar charts and pie charts using ChartJs, with data fetched from php and mysql. Specifically, I want to generate a bar chart that illustrates the statistics of male and female students, along with the total number of students. The des ...

Mastering the ng-submit directive for AngularJS

Having an issue with my form that submits a location to Google's Geocoder and updates the map with the lat/long. When using ng-click on the icon, it requires double clicking to work properly. And when using ng-submit on the form, it appends to the URL ...