How to flatten an array in JavaScript without relying on the reduce library

In my code, there is a nested array called $scope.instruments which contains the following:

Collapsed view:

https://i.sstatic.net/Aii9N.png

Expanded view:

https://i.sstatic.net/Fh5Bz.png

Additionally, I have an object:

https://i.sstatic.net/qd8Xn.png

This object has two arrays: AttributeID and SPAttributeRefID.

Currently, I am flattening the $scope.instruments array using the reduce function as shown below:

$scope.instruments = $scope.instruments.reduce(function (result, instrument) {
    result[instrument.ID] = instrument;
    return result
}, {});

Next, I extract the AttributeID from the object and assign it to a variable in this manner:

$scope.recordInstrument = $scope.instruments[data.AttributeID[0]].ID;

Instead of using the reduce function, I would like to achieve the same result using a loop. I tried experimenting with a for loop but haven't been successful so far:

var arrInstruments = $scope.instruments;
var arrLength = arrInstruments.length;

for (var i = 0; i < arrLength; i++) {
    console.log(arrInstruments[i]);                                
}

If anyone can assist me in converting the code that uses reduce to use a loop while retaining the functionality of assigning AttributeID, I would greatly appreciate it.

Thank you very much.

Answer №1

Here is a code snippet that can accomplish what you are searching for:

let instrumentArray = $scope.instruments;
let arrayLength = instrumentArray.length;
let resultObject = {}
for (let i = 0; i < arrayLength; i++) {
    resultObject[instrumentArray[i].ID] = instrumentArray[i];
}
// The resultObject now holds the desired data.

I must admit, I'm not entirely sure of the purpose behind this functionality.

The image you provided:
https://i.sstatic.net/Aii9N.png

It's important to note that this is not a multidimensional array. Your console simply displays large arrays in an abbreviated manner for efficiency.

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

Using HTML and CSS to generate an alpha mask on top of an image

I am currently working on a website and I am looking to create an effect where an image is masked by an overlay. The goal is to achieve a "fade out" effect, without any actual animation, but rather make it appear as if the image is gradually fading into th ...

Error: Property ID was not followed by a colon

There is a Syntax Error: missing : after property id near '<img src="loading.gif" />';` <script> $(document).ready(function() { $("#client").on("change", function() { var clientid=$("#client").val(); ...

Guide on converting a timestamp output in Node.js

I ran a query to retrieve TimeStamp data from MYSQL using Node JS, and the output is as follows: MyDate: Thu Apr 28 2016 07:02:45 GMT+0700 (SE Asia Standard Time) Can anyone help me convert it to yyyy-mm-dd hh:mm:ss format? ...

Looking to control TextView and ImageView with a single button press, utilizing arrays and switch cases? Additionally, seeking code for implementing a previous button in an Android app?

Hey there! I am new to Android development and currently working on enhancing an activity in my app. This activity consists of a total of 10 views, including 7 text views, 2 image buttons, and 1 image view. My goal is to allow users to navigate through the ...

Having trouble updating the route with the $location service, even after attempting to use $scope.apply

After trying to utilize the location service with no success, I am left wondering why my view isn't changing even after using either $scope.$apply() or $scope.apply. Prior to posting my question, I conducted thorough research on similar inquiries but ...

Combining jQuery with AngularJS for optimal web development outcomes?

As someone new to AngularJS, this project is challenging my knowledge of ng-repeat and controllers. Objective : My goal is to have the guitars appear when an option is selected from the drop-down menu and the button is clicked using ng-repeat. Currently, ...

Selenium is encountering a validation error when selecting a value from a Drop Down menu

My current project involves automating website testing through selenium. I have encountered a scenario where I need to fill in a mandatory drop-down field. The code snippet I am using to select the drop-down value is as follows: select = Select(find_eleme ...

Encountered difficulties implementing Chart.js with Angular2

Greetings! I am currently attempting to utilize one of the Charts provided by http://www.chartjs.org, however, I seem to be encountering difficulties in getting it to function properly. I have followed the documentation by installing 'npm install char ...

What is the best way to pass data from the server to a Vue CLI application?

I am looking for a way to connect my Vue CLI app to a server back-end. The server will send a view template along with data payload, and I need to inject that payload as JSON into the Vue app as a data property. Here is a snippet of the index.html file ge ...

Avoiding code execution by injections in Javascript/Jquery

Currently, I'm fetching JSON data for a .getJSON function in Jquery. To ensure the data's security, I am considering using .text (I believe this is the correct approach). The JSON has been successfully validated. Below is the script that I am cu ...

Having difficulties including the Stack Overflow website within an iframe

I've been attempting to embed the Stack OverFlow website into an HTML page using an iFrame, but I'm running into some issues. Oddly, when I tried embedding my other two websites, they displayed correctly, but Stack OverFlow is not showing up on m ...

Displaying a plethora of data points on a single graph using jQchart with a

I'm currently using jQchart to showcase a graph, but I'm running into an issue with the title property only displaying a single line of text. The current title being displayed on the graph is as follows: text: chartTypeText + ': ' + ch ...

Ways to avoid unintentional removal of contenteditable unordered lists in Internet Explorer 10

How can I create a contenteditable ul element on a webpage while avoiding the issue in Internet Explorer 10 where selecting all and deleting removes the ul element from the page? Is there a way to prevent this or detect when it happens in order to insert ...

Organizing data in TypeScript

Is there a way to alphabetically sort this list of objects by name using TypeScript? "[{name:"Prasanna",age:"22",sex:"Male",Designation:"System Engineer",Location:"Chennai"}, {name:"Nithya",age:"21",sex:"Female",Designation:"System Engineer",Location ...

Encountered a parsing error when attempting to integrate SCSS with webpack and babel setup

I am facing an issue while trying to integrate SCSS into my webpack and babel setup. When running npm run build, I encounter an error that I'm unfamiliar with. As a beginner in using webpack and babel, I'm unsure about the necessary changes requ ...

Looking for non-case-sensitive letters in a text input field

Having trouble with case-insensitive search using jquery? The search option seems to be working fine, but there's an issue with uppercase and lowercase letters in the content. Check out my full code on jsfiddle where if I search for "senthil" it doesn ...

Is it possible to execute a task following a particular Websocket.send() in JavaScript?

After sending a message to a websocket, I am trying to send a POST request using callbacks. I attempted the following approaches: socket.send(message,function(){...}); and function sendsocket(message, callback){ socket.send(message); callback; } and ca ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

Once more, objects cannot be used as a child element in React

I understand that there are similar questions about this topic, but I am struggling to approach it in a different way. I really need an array of objects to be inside a map. I have created an array to map it, but I need to find different information to disp ...