What is the best way to combine two arrays into a single array using AngularJS?

Here is a code snippet:

$scope.studentDetails=[];

$scope.studentDetails=[0][id:101,name:one]
                      [1][id:102,name:two]
                      [2][id:103,name:three] 

$scope.studentMarks=[];

$scope.studentMarks=[0][id:101,marks:78]
                    [1][id:102,marks:89]

I have two arrays. The first array contains properties like id and name, while the second array contains properties like id and marks. I need to combine these two arrays into one single array with the desired output:

$scope.studentDetails=[0][id:101,name:one,marks:78]
                      [1][id:102,name:two,marks:89]
                      [2][id:103,name:three,marks:null]

Answer №1

Using Lodash's zip() function should accomplish that task, assuming your JavaScript code is correct to begin with.


$scope.dataCombined = _.zip($scope.studentInfo, $scope.studentGrades);

Answer №2

I have found the solution

let studentsArray = [];
_.each($scope.studentDetails, function(student) {
  let data = _.findWhere($scope.studentMarks, {"id": student.id});
  if (!_.isUndefined(data)) {
    studentsArray.push({id: student.id, name: student.name, marks: data.marks});
  } else {
    studentsArray.push({id: student.id, name: student.name, marks: "null"});
  }
}

Answer №3

Hey there, here is an example of how you can utilize the push method:

$scope.studentDetails.push({'id':'101','name':'one','marks':'78'});
$scope.studentDetails.push({'id':'102','name':'two','marks':'78'});
$scope.studentDetails.push({'id':'103','name':'three','marks':'78'});

If you want to use a loop to append data, you can do it like this:

for(i = 0; i < studentResult.length; i++){
    $scope.studentDetails.push(studentResult[i]);
}

Answer №4

When utilizing _.zip, the object array merges two arrays into a single array where each array element is also an array.

To create a merged object array with _.zip, you can employ .map and .extend as shown below:

var studentDetails = [{ id: 101, name: 'one' }, { id: 102, name: 'two' }, { id: 103, name: 'three' }];
var studentMarks = [{ id: 101, marks: 78 }, { id: 102, marks: 89 }];

var mergedArray = _.zip(studentDetails, studentMarks); // Each element is also an array like [ [{ id: 101, name: 'one' }, { id: 101, marks: 78 }] ]

var studentDetails = _.map(mergedArray, function (item) { return _.extend(item[0], item[1]); }); // [{ id: 101, marks: 78, name: 'one' }, ..]

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

The completion action is never carried out

I am currently facing an issue with one of my JavaScript functions. I have several $.ajax calls throughout my webpage followed by .done(), and they all seem to be functioning properly, except for one. Can anyone identify what could be causing the error? m ...

Shift every ng-repeat child element and display the updated outcome

I am looking to create an animation that will shift all items displayed using the ng-repeat directive to the left, hide the first item, and show a new element in place of the last one. The elements are being displayed using the ng-repeat directive from a ...

Changing a single state in React results in the modification of both states simultaneously

Whenever I attempt to modify one state, I find that another state is inexplicably changing as well. I've scoured my code for the issue but can't seem to pinpoint it. What steps should I take next? Here's the snippet of code in question: impo ...

"Troubleshooting: Why Won't insertAfter Function Work with

I have a p Element that I want to wrap inside a span tag. Then, I need to insert it after another p tag with the id output. Despite my attempts, the insertAfter function is not working as expected. $mytext = $("p#test").html(); $myspan = "<span styl ...

How can we address the tagging directive problem of binding tags as an array of JSON objects and ensuring that tagging functions properly with the ng-keypress event?

Check out this plnkr example. I'm having trouble binding my tags list with ng-model. I want to bind the tags as an array of objects on a function call using ng-keypress, and then post it to a json file in a specific format. Here is what I am looking f ...

Passing a string to a function in AngularJS through ng-click

How can I pass a string to a function using ng click? Here's an example: HTML <a class="btn"> ng-click="test(STRING_TO_PASS)"</a> Controller $scope.test = function(stringOne, stringTwo){ valueOne = test(STRING_TO_PASS); } Edit - ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

Stop procrastinating and take action before the JavaScript function concludes

Currently, I am experimenting with onkeydown events to capture the input value in a textarea, process it through a PHP file using Ajax post method, and display the result in an external div. However, the issue is that whenever a key is pressed, I am unable ...

How to easily transfer a JSON file to a server using Vue and Node.js

As a newcomer to the world of Node.js and Vue development, my goal is to establish a seamless process for users to create and upload a JSON file to the server when they save data in a form. This process should occur effortlessly in the background, allowing ...

Encountering an issue in Laravel when trying to retrieve data using relationships and the paginate() method

When I try to fetch data using paginate(10), Vue.js does not work. However, if I use paginate(5), it works fine. The code in the Controller with relationships in the model files is working fine and returns a 200 OK response. $results = Posts::with([' ...

Switching to a jQuery IF statement instead of a FOR loop allows for more streamlined

I recently made a request to sqlite and am fetching data using the code snippet below: var rows = results.rows; alert(rows.length); for (var index = 0; index < rows.length; index++) { var x = rows.item(index); $( ...

Turn off javascript on a website that you are embedding into another site

Is it feasible to deactivate JavaScript on a website you are attempting to embed? If the website is working against your embedding efforts, could you effectively neutralize all their JavaScript, even if it requires users to engage with the site without J ...

In JavaScript, when a div element contains an iframe, the click event will not trigger on the div

Check out this sample HTML markup: <div> <iframe></iframe> </div> The iframe is set to fill the outer div. I've added an event handler to the div click event: div.addEventListener("click", function () { console.log( ...

adjusting the size of the sidebar at the top to ensure that it does not overlap the top menu

I have a sidebar on my page that opens vertically when I click a button. The sidebar covers the company logo and name, so I want to make it smaller. Here is the code for the sidebar: <body> <nav class="navbar navbar-dark bg-dark" ...

Trying to convert <image> from canvas to png or base64 is not functioning properly

Currently, I am dealing with a grid div element that contains various HTML tags such as <div>, <p>, and <img>. I need to convert this grid to canvas and then encode it to base64 for saving on the server using PHP. Can someone assist me i ...

Is it possible to use file upload for sending via Ajax's POST method?

Let's talk about the scenario at hand Here's what happens in a single form: 1) The user clicks on the 'browse' button, which opens a dialog to select an image file for uploading. Example: input id='img_upload' name="ufile" ...

What is the best way to conceal an element by clicking anywhere other than on the element itself?

Currently, I am utilizing jQuery's toggle method to display or hide a page element when another specific page element is clicked. jQuery('a#mobile-search-icon).click(function(){ jQuery('#searchBox').toggle('slow'); }); ...

Using the .ajax() function with jQuery to retrieve data and then using .find() on that data

Currently I am facing an issue while trying to extract the body tag from the result of the .ajax() call. Instead of getting the desired result, I only see undefined logged into the console... This is the section of code causing the problem: $(document).r ...

Switching between sockets on a rotational basis

Imagine there is a division in the HTML file, and an interesting game is being played where each player has the opportunity to change the color. However, there’s a twist – they can only switch colors after the other player has taken their turn. The pla ...

Update the content of an HTML element without having direct access to the HTML code

I am currently in the process of creating a website using a website builder, and I am interested in customizing the default message that is displayed when a required field in the website form is left empty. The form in question is an integral part of the w ...