Link the index of a nested array of numerical values to the corresponding index of an array containing strings

In my current project, I am trying to connect the array elements from foo3.flat() with the elements in foo2. For instance, if the 0th index in foo2 is 'address1' and the 0th index of foo3 is [1,2,3], all the individual numbers in [1,2,3] should be associated with 'address1'. This is how obj is currently mapped out.

Value of obj

{
  address1: [ 1, 2, 3 ],
  address2: [ 4, 5 ],
  address3: [ 6, 7, 8, 9 ],
  address4: [ 10 ]
}

Code

var foo1 = []

var foo2 = [
  'address1',
  'address2',
  'address3',
  'address4'
]

var foo3 = [
  [1, 2, 3],
  [4, 5],
  [6, 7, 8, 9],
  [10]
]

var foo4 = [
  [11, 12, 13],
  [14, 15],
  [16, 17, 18, 19],
  []
]


var foo5 = [
  [
    [111, 111, 111],
    [222, 222, 222],
    [333, 333, 333]
  ],
  [
    [444, 444, 444],
    [555, 555, 555]
  ],
  [
    [666, 666, 666],
    [777, 777, 777],
    [888, 888, 888],
    [999, 999, 999]
  ],
  []

]

var obj = {}

foo2.forEach((key, i) => obj[key] = foo3[i])

foo3 = foo3.flat()
foo4 = foo4.flat()
foo5 = foo5.flat()


for (var i = 0; i < foo3.length; i++) {

  foo1.push({
    key1: '',
    key2: foo3[i],
    key3: foo4[i],
    key4: foo5[i]
  })
}

console.log(foo1)

Result

[
  { key1: '', key2: 1, key3: 11, key4: [ 111, 111, 111 ] },
  { key1: '', key2: 2, key3: 12, key4: [ 222, 222, 222 ] },
  { key1: '', key2: 3, key3: 13, key4: [ 333, 333, 333 ] },
  { key1: '', key2: 4, key3: 14, key4: [ 444, 444, 444 ] },
  { key1: '', key2: 5, key3: 15, key4: [ 555, 555, 555 ] },
  { key1: '', key2: 6, key3: 16, key4: [ 666, 666, 666 ] },
  { key1: '', key2: 7, key3: 17, key4: [ 777, 777, 777 ] },
  { key1: '', key2: 8, key3: 18, key4: [ 888, 888, 888 ] },
  { key1: '', key2: 9, key3: 19, key4: [ 999, 999, 999 ] },
  { key1: '', key2: 10, key3: undefined, key4: undefined }
]

Expected Result

[
  { key1: 'address1', key2: 1, key3: 11, key4: [ 111, 111, 111 ] },
  { key1: 'address1', key2: 2, key3: 12, key4: [ 222, 222, 222 ] },
  { key1: 'address1', key2: 3, key3: 13, key4: [ 333, 333, 333 ] },
  { key1: 'address2', key2: 4, key3: 14, key4: [ 444, 444, 444 ] },
  { key1: 'address2', key2: 5, key3: 15, key4: [ 555, 555, 555 ] },
  { key1: 'address3', key2: 6, key3: 16, key4: [ 666, 666, 666 ] },
  { key1: 'address3', key2: 7, key3: 17, key4: [ 777, 777, 777 ] },
  { key1: 'address3', key2: 8, key3: 18, key4: [ 888, 888, 888 ] },
  { key1: 'address3', key2: 9, key3: 19, key4: [ 999, 999, 999 ] },
  { key1: 'address4', key2: 10, key3: undefined, key4: undefined }
]

var foo1 = []

var foo2 = [
  'address1',
  'address2',
  'address3',
  'address4'
]

var foo3 = [
  [1, 2, 3],
  [4, 5],
  [6, 7, 8, 9],
  [10]
]

var foo4 = [
  [11, 12, 13],
  [14, 15],
  [16, 17, 18, 19],
  []
]


var foo5 = [
  [
    [111, 111, 111],
    [222, 222, 222],
    [333, 333, 333]
  ],
  [
    [444, 444, 444],
    [555, 555, 555]
  ],
  [
    [666, 666, 666],
    [777, 777, 777],
    [888, 888, 888],
    [999, 999, 999]
  ],
  []

]

var obj = {}

foo2.forEach((key, i) => obj[key] = foo3[i])

foo3 = foo3.flat()
foo4 = foo4.flat()
foo5 = foo5.flat()

for (var i = 0; i < foo3.length; i++) {
  foo1.push({
    key1: '',
    key2: foo3[i],
    key3: foo4[i],
    key4: foo5[i]
  })
}

console.log(foo1)

Answer №1

Below is the code snippet that will generate the desired output:

var arr1 = [];

var arr2 = [
  'item1',
  'item2',
  'item3',
  'item4',
];

var arr3 = [
  [1, 2, 3],
  [4, 5],
  [6, 7, 8, 9],
  [10],
];

var arr4 = [
  [11, 12, 13],
  [14, 15],
  [16, 17, 18, 19],
  [],
];


var arr5 = [
  [
    [111, 111, 111],
    [222, 222, 222],
    [333, 333, 333]
  ],
  [
    [444, 444, 444],
    [555, 555, 555]
  ],
  [
    [666, 666, 666],
    [777, 777, 777],
    [888, 888, 888],
    [999, 999, 999]
  ],
  [],
];

const mapping = new Map();

for (let i = 0; i < arr2.length; i++) {
  const maxLen = Math.max(arr3[i].length, arr4[i].length, arr5[i].length);
  for (let j = 0; j < maxLen; j++) {
    mapping.set('keyA', arr2[i]);
    mapping.set('keyB', arr3[i][j]);
    mapping.set('keyC', arr4[i][j]);
    mapping.set('keyD', arr5[i][j]);
    const object = Object.fromEntries(mapping);
    arr1.push(object);
    mapping.clear();
  }
}

console.log(arr1);

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

Setting input type to date with full width using jQuery Mobile

Currently working on a web project utilizing jQuery Mobile 1.1.1 and looking to incorporate a <input type="date" /> that spans the entire width of the page. However, encountering a peculiar issue (noticing a gap where an arrow should be displayed) sp ...

Automatically select all options in MUI Autocomplete by default

Is there a way to have all the values in the autocomplete drop down automatically selected by default when the page loads? I've been experimenting with this example but haven't found a solution yet. If you know how to achieve this, please share! ...

Optimizing ajax speed when loading large lists from the backend

For the CRUD operations in my application, I retrieve all items from the backend and display them on the front-end by looping through them using JavaScript, specifically utilizing ajax. Picture my app as a to-do list. Whenever a user adds a new item, do I ...

Arrange a JSON response in descending order and filter out specific values

Currently, I'm encountering a challenge when trying to extract a specific attribute from my JSON response. The issue arises when I attempt to sort the results based on the `percentage_match` in descending order. Once sorted, my goal is to create an ar ...

Monitor the scrolling progress across four separate HTML pages without the percentage decreasing when scrolling back up

I am in the process of developing an e-learning platform and I would like to include a scrolling indicator that visually represents the progress of pages read. The website consists of four HTML pages, with each page corresponding to 25% of the scroll bar. ...

How to use Ionic 3 to automatically scroll ion-scroll content all the way to the bottom

My ion-scroll component is experiencing some challenges <ion-scroll scrollY="true" style="height: 52vh;"> {{ text }} </ion-scroll> The content inside the ion-scroll keeps expanding, exceeding the designated height. Users can manually scroll ...

Images following do not have jQuery hidden

I am facing an issue with a small test script that is designed to hide images on button click. However, the problem I am encountering is that it only hides the first image out of three and then ceases to hide the subsequent ones. Below is the code snippet ...

Sort Json by date in LogicApp

I have a JSON data structure generated within a logic app, and I am looking to extract only the objects with the maximum date. Essentially, I want to filter out duplicate records for each object and only keep the one with the latest date. [{ "Fech ...

What methods are available in JavaScript regex for validating city names?

var cityRegex = /^[a-zA-z] ?([a-zA-z]|[a-zA-z] )*[a-zA-z]$/; is the regular expression I attempted to create. However, it fails when inputting a city name like "St. Petersburg." Update: It seems challenging to create a perfect regex pattern for city name ...

Trigger event when the useRef element's height surpasses zero

I have a large list of photo thumbnails, and I need to ensure that one of the thumbnails scrolls into view when the list is loaded. The photos are generated using the map function, and the container div of one of the thumbnails will be assigned a ref. I ...

Achieving a multiline ellipsis (clamp) across various levels of HTML tags, compatible with popular browsers like IE and Firefox

After conducting extensive research, I finally discovered a reliable method for implementing multiple Line Ellipsis (using JS, as plain CSS is not effective). Despite exploring 100 different Google results and Q/As, this is currently the only solution that ...

Display loading animation until Google Maps is fully loaded - Utilizing AngularJs

Is there a way to check the readiness of Google Maps before displaying it? I'd like to show a preloader block while the Google Maps is loading. Here is the factory code I am using: var map = false; var myLatlng = new google.maps.LatLng(48.6908333333 ...

What is the best way to change the format of a datetime?

While working with sailsjs(node.js), I have successfully retrieved all the data from a MySQL database and displayed it in a jtable. However, the date format is currently showing as YYYY-MM-DDTHH:mm:ss.000Z. I am looking to convert this format (YYYY-MM-DDT ...

directive for form validations is malfunctioning

I am a beginner with AngularJS and I'm currently working on writing a directive that wraps an input box inside a form tag, followed by a 'div' element which includes validation. Unfortunately, the validation is not functioning as expected. Y ...

Updating the active navbar link with JavaScript in ASP.NET Core Razor Pages

When navigating through my Razor Pages, I need to dynamically change the color of the navbar links. I attempted using JavaScript, but encountered issues with the pages getting rerendered each time, preventing me from toggling the elements. Here's wha ...

Emphasize Expandable Sections based on Search Term

I have been working on developing an HTML page for my company that will showcase a list of contacts in an "experts list". Currently, the list is structured using collapsible DIVs nested within each other. Additionally, the HTML page features a search func ...

The outcome of AES encryption varies when comparing Node JS with C# programming languages

In a particular scenario, I need to encrypt and transmit text using the AES 256 algorithm. The decryption process will be handled by client-side C# code. Here is the encryption code in JavaScript: const crypto = require('crypto'); algorithm = ...

Java: Implementing an IF statement within a for loop

When the user clicks on option 2 in the main menu, they can deposit funds into an account of their choice. In this example, let's consider three accounts with IDs '1001', '1002', and '1003'. The code below includes a for ...

Here's a step-by-step guide on passing the value of an input field from JavaScript to a PHP file and retrieving the returned values

Below you will find the HTML code I'm currently working with: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Pagination with composite queries in Firestore allows for efficient retrieval of

Currently I am attempting to paginate a composite index query, let size = data.length let lastElement = data[size-1].commentCount db.collection('user-content').orderBy('commentCount','desc').orderBy('likes', 'd ...