Is there a way to efficiently transform an 'Array of Objects' with values 'Array of Object' into an array of Objects with individual array values using JS/lodash?

I utilized the lodash library to divide arrays into chunks (batches).

let values = {
    'key1' : [lotsOfValues1],
    'key2' : [lotsOfValues2]
};
let keys = ['key1', 'key2'];
let arrObj = [];
keys.forEach((key) => {
    arrObj.push([key] : lodash.chunk(values[key], 20)) // it will break lotsOfValues arrays into chunks of size 20
});
/* Now arrObj = [
  {
    key1: [[someVals1], [someVals2], [someVals3]],
  },
  {
    key2: [[someVals4], [someVals5]],
  },
];
*/

Is there a more efficient way to convert an array of Objects -

const arrObj = [
      {
        key1: [[someVals1], [someVals2], [someVals3]],
      },
      {
        key2: [[someVals4], [someVals5]],
      },
    ];

to an array of Objects where each object has individual array elements instead of an array of objects. For example -

const arrObjTransformed = [
      { key1: [someVals1] },
      { key1: [someVals2] },
      { key1: [someVals3] },
      { key2: [someVals4] },
      { key2: [someVals5] },
    ];

any assistance on this matter would be greatly appreciated.

I attempted to iterate through arrObj and nested loops to create a new object with each value, continuously updating the final output array.

However, I believe there might be a cleaner solution to accomplish this task.

Answer №1

If you want to traverse an array of objects using _.flatMap(), it allows you to loop through the array and then the object's properties, mapping each chunk into new objects with specific chunks.

const { flatMap, map } = _

const arr = [{
    'key1': [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
  },
  {
    'key2': [[4, 4, 4], [5, 5, 5], [6, 6, 6]],
  },
  {
    'key3': [[7, 7, 7]]
  }
]

const result = flatMap(arr, obj => 
  flatMap(obj, 
    (v, k) => map(v, chunk => ({
      [k]: chunk
    }))
  )
)
console.log(result)
.as-console-wrapper { max-height: 100% !important; }
<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>

Alternatively, you can directly work with the original object and create both chunks and the desired structure in one go:

const { flatMap, map, chunk } = _

const obj = {
  'key1': [1, 1, 1, 2, 2, 2, 3, 3, 3],
  'key2': [4, 4, 4, 5, 5, 5, 6, 6, 6],
  'key3': [7, 7, 7]
}

const result = flatMap(obj, (arr, key) => 
  map(chunk(arr, 3), chunk => ({
    [key]: chunk
  }))
)
  
console.log(result)
.as-console-wrapper { max-height: 100% !important; }
<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>

Answer №2

Let's attempt it by looping through an array of objects, then multiplying each key by the arrays associated with that key. Here is an example:

const arrObjects = [{
    'key1': [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
  },
  {
    'key2': [[4, 4, 4], [5, 5, 5], [6, 6, 6]],
    'key3': [[7, 7, 7]]
  }
]

var resultArr = []
arrObjects.forEach(function(object) {
  Object.keys(object).forEach(function(key) {
    var arrayOfArrays = object[key];
    arrayOfArrays.forEach(function(array) {
      var newElement = {}
      newElement[key] = array;
      resultArr.push(newElement)
    })
  })
})

console.log(resultArr)
.as-console-wrapper {
  max-height: 100% !important
}

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

Develop a JSON object containing a JSON array within an Android application

"ORDERDETAIL":[ { "Description":"xyz", "Quantity":"3", "Unit Price":"55", "No.":"7", "Line No.":"30", "Document Type":"2", "Document No.":"105" }, { "Description":"abc", "Quantity":"8", "Unit Price":"12", "No.":" ...

Automatically load VueJS components based on the prefix of the tag

I am currently working on defining components based on the prefix when Vue parses the content (without using Vuex). While exploring, I came across Vue.config's isUnknownElement function but couldn't find any documentation about it. By utilizing ...

Decisive presentation of Laravel data in an appropriate structure

In my project using Laravel, I am developing an API to query a database and display a simple output. The query structure I am using is as follows: $name = new TableName() ; //Object storing tablename $result=DB::table($name->getMyTableName()) // Gettin ...

Personalizing Material-UI Components using Styled-Components

My attempt to modify the props of a material-ui Grid component using styled-components was not successful. I initially tried: const NavGrid = styled(Grid)` direction: 'row'; ` Unfortunately, this approach did not yield the desired result. T ...

Begin a new countdown timer upon clicking the next button

Currently, I am developing a bid auction website and I have implemented a countdown timer script. The timer works perfectly on the initial window load. However, when I click on the restart button, it fails to reset the countdown timer to a new value. < ...

Using ngFor results in duplicate instances of ng-template

I'm facing a challenge with the ngFor directive and I'm struggling to find a solution: <ng-container *ngIf="user.images.length > 0"> <div *ngFor="let image of images"> <img *ngIf="i ...

What are some effective ways to utilize localstorage efficiently?

I've been working on creating a variable that stores its value across multiple pages using local storage. However, I've encountered an issue where the variable is not being saved, and there are no error messages to help diagnose the problem. Her ...

Retrieve the JSON data once the user has applied the filter

Is there a more efficient way to improve the performance of handling an extremely large JSON file with 5000 keys and 5 values each? Currently, I am using AngularJS with a backend in Drupal 7. Here is my view: <ul class="list-group border-0"> < ...

"Troubleshooting conversion issue in Laravel when converting integer to string in JSON response

When working in Laravel, I have encountered an issue with outputting data using the following command: response()->json($data, $status, [])->send(); This command has been causing all numerical values from the database to be converted into strings. T ...

Duplicate key error occurred in the collection resulting in Error Handling: E11000

Encountering an issue with the user model I'm utilizing alongside Mongoose and MongoDB to create profiles in my database. The process works smoothly when posting a single user, but throws an error upon logging out and attempting to add another: { ...

Creating a dynamic drag-and-drop layout in React using react-grid-layout

Utilizing the react-grid-layout package for implementing drag-drop and resize components, I have successfully achieved the functionality outlined in the documentation. Description of My Issue My challenge lies in creating a dynamic UI where the layout is ...

Populate an ng-repeat table again while maintaining its original sorting order

Incorporating a table filled with data fetched from a webservice using the ng-repeat directive, I have enabled sorting functionality for all columns. Additionally, at regular intervals, the application polls the webservice to retrieve updated data. This o ...

Tips for accessing a DOM element's ::before content using JavaScript

Is there a way to retrieve the content of a DOM element's ::before pseudo-element that was applied using CSS3? I've attempted several methods without success, and I'm feeling very confused! // https://rollbar.com/docs/ const links = docum ...

What is the process for converting an attribute ArrayList<String>, ArrayList<Integer>, or ArrayList<MYCLASS> from a JSON object into a Java object?

Being a novice in programming, I am currently attempting to save my objects as JSON in a text file. However, I have encountered difficulties when passing the JSON object to my constructor. Here is the structure of my 'Aluno' class: public class ...

Verify whether the JSON string is equal to 1, then show "one"; if it is 2

My JSON array response contains item locations with IDs such as "1", "2", etc. Instead of displaying the numbers, I want to show the corresponding location names on my site. How can I check and change these values before setting text? Using ready values fr ...

How can you effectively transfer arguments from one component to another using router.push() in Vue.js?

I need help with implementing a feature where upon clicking the edit button in a row, all the details from that particular row should be passed to a form component. I want to populate the form fields with default values from the parameters provided. Can ...

Exploring the method of inserting an element into a nested array using JavaScript's ES6 features

Let's say I understand how to use the spread operator to add an element to a regular array in ES6. const arr = ["a","b"] const newArr = [...arr, "c"] This would result in ["a","b","c"] But when it comes to implementing this with a nested array, like ...

Getting JSON data from an Angular JS controller can be achieved by utilizing the built-in

My user login function includes a method called logincheck, which takes in parameters and sends a request to the server. Upon success, it redirects the user to the dashboard with the member ID. this.logincheck = function(log) { var pa ...

Expanding the functionality of the Ember JSONAPIAdapter for retrieving JSON data from a specified URL

As a newcomer to Ember.js, I am currently delving into understanding how Ember works. One issue I have encountered is calling my Django API from an Ember.js route using the following code: this.store.findAll('MYMODEL', 'ANOTHER_MODEL_ID&apos ...

Refresh text displayed on a button with the help of setInterval

I need help updating the text on a button with the id fixed-button at regular intervals. Here is the code I am currently using: <script type="text/javascript"> $(function() { $('#fixed-button').setInterval(function() { ...