Exploring the Differences Between Arrays of Objects and Arrays in JavaScript

While working on a project for a client, I encountered an interesting problem. I have two arrays - one with objects and one with values. The task is to populate the array of objects with new objects for every item in the value array. To clarify, here is the code snippet and the expected output:

// Arrays: worksheet and data
var worksheet   = [{"student_name": "Test 1", "file": "some_file_name.txt"}, {"student_name": "Test 3", "file": "some_file_name.txt"}]
var data        = {"student_names": ["Test 1", "Test 2", "Test 3", "Test 4"]}

The goal is to iterate through data.student_names and add students that are not already in the worksheet.

// Expected Output:
var worksheet = [
    {"student_name": "Test 1", "file": "some_file_name.txt"},
    {"student_name": "Test 3", "file": "some_file_name.txt"},
    {"student_name": "Test 2", "file": ""}, // New student
    {"student_name": "Test 4", "file": ""}, // New student
]

Answer №1

const studentData = [
  { 'name': 'Alex', 'file': 'document1.txt' },
  { 'name': 'John', 'file': 'document2.txt' }
]

const testData = { 'names': [ 'Alex', 'Lisa', 'John', 'Mike' ] }

const resultData = testData['names']
  .map(name => {
      let record = studentData.filter(item => item['name'] === name)
      let file = record.length === 0 ? '' : record[0].file
      return { 'student_name': name, 'file': file }
    }
)

console.log(resultData)

Answer №2

Approach

We will iterate over the list of student names stored in data.student_names and verify if each name exists within the worksheet. If a match is found, we will add the corresponding student object to the foundArr; otherwise, we will create an entry for the student name with an empty file in the notFoundArr. Finally, we will merge both arrays to obtain the desired output.

Implementation

const worksheet = [{"student_name": "Test 1", "file": "some_file_name.txt"}, {"student_name": "Test 3", "file": "some_file_name.txt"}];
const data = {"student_names": ["Test 1", "Test 2", "Test 3", "Test 4"]};
let foundArr = [];
let notFoundArr = [];
data.student_names.forEach(s => {
  let studentFound = worksheet.find(ws => ws.student_name === s);
  if (studentFound !== undefined){
    foundArr.push(studentFound);
  }
  else {
    notFoundArr.push({"student_name": s, "file":""});
  }
});
let result = foundArr.concat(notFoundArr);
console.log(result);

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

Utilizing group_concat with objects in PHP

Seeking assistance with retrieving specific data from a PHP object loaded with a MySQL row that utilizes the group_concat function. Upon var_dumping the $row variable, the structure includes a key labeled group_concat(resourceId), causing difficulty in ac ...

Sending an associative array to Javascript via Ajax

Learning a new programming language is always a great challenge. Can someone guide me on how to efficiently pass an associative array to JavaScript using AJAX? Below is a snippet of code from server.php: $sql = "SELECT Lng, Lat, URL FROM results LIMIT ...

The issue of variable stagnation in Firefox content script while utilizing self.port.on

I'm having trouble updating the version var as intended. When I try to update it with the following code: self.port.on("get-version", ver => { version = ver; alert(version); }); An alert pops up displaying the correct version number, but the HTML ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Node.js server for Cross-Origin Resource Sharing

I'm brand new to Node.js and I'm trying to run some example code, but I keep encountering CORS issues. Server.js var http = require('http'); var io = require('socket.io'); server = http.createServer(function(req, r ...

What is the best way to showcase a photo selected using an HTML input within a div container?

My goal is to select a photo from a folder and display it on a webpage, but I have struggled to find a working solution. Can this be achieved using just basic HTML, CSS, and JS? I am new to web development, so please forgive me for any beginner questions. ...

Creating dynamic transformations and animations for characters and words within a paragraph in 3D

Looking to add animation effects to specific parts of a paragraph, but transforming the entire box instead. Remembering seeing a solution on StackOverflow before, now regretting not saving it. Spent over an hour searching for a similar answer without succ ...

Discovering the method to extract a Specific Form Field value with JQuery

Recently, I encountered a form that looked like this: <form id="post_comment" action="cmt.php" method="post"> <input type="hidden" name="type" value="sub" /> <textarea id="body"></textarea> </form> To interact with the ...

What is the method for assigning classes to a Vue.js Functional Component from its parent component?

Imagine a scenario where I have a functional component: <template functional> <div>Some functional component</div> </template> Now, when I render this component within a parent element with classes: <parent> <som ...

Firebug mistakenly detects phantom errors

<div id="video-player" data-src="http://www.youtube.com/embed..."></div> Inspect Element - Browser Developer Tools: Error: Access to property 'toString' denied I scanned the entire page (Ctrl+F) and could not find any reference t ...

Using a PHP switch case statement with an HTML multiple select dropdown

I am facing an issue with my HTML multiple select box: <option value="1">First choice</option> <option value="2">Second choice</option> <option value="3">Third choice</option> Using jQuery, ...

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

Reveal each element individually upon clicking the button

I am trying to display 5 div elements one by one when clicking a button, but the current code is not working. I am open to alternative solutions for achieving this. Additionally, I want to change the display property from none to flex in my div element. ...

Is it possible for a popup to appear without any user interaction

Do you ever wonder how certain websites are able to trigger pop-ups without being blocked by Chrome's pop-up blocker? I had always thought that pop-up blockers only allowed window.open if it was initiated by a user action. However, the situation seem ...

Tips for implementing both an onChange and onSubmit event for a MUI TextField

I'm currently working with React and MUI and have created a form like the following: const handleUserInput = (event) => { set_user_input(event) } const handleSubmitForm = () => { if (user_input == 'help'){ ...

Styling pagination using CSS and jQuery

I am looking to display 3 sections in a simple, paginated way that mimics tabs. I am trying to implement the logic where when a pagination item is clicked and has the 'active' class, it should show the corresponding block. However, I am strugglin ...

Guide to removing selected value from a combobox in Angular

I am working on a simple HTML file that consists of one combobox and one clear button. I want the clear button to remove the selected value from the combobox when clicked. Below is my code: mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayou ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...

Transmit both image and JSON data in a single response using Node.js and Express

I'm in the process of building a web API using Node.js and Express and my goal is to send back both an image and JSON data in a single response. I came across a solution that involves specifying headers at , but I'm looking for a way to achieve t ...

Every time I try to reload the page in my comment app, all the comments mysteriously

I've noticed that my comment app is functioning properly, but the issue arises when I refresh the page and the comments disappear. Upon checking the log, it seems that the body is inserted into the comments table (it is saved). What could be going wro ...