Javascript code for populating multiple objects with new items using a nested for loop

Trying to articulate my thoughts, I am interested in linking a list of skill sets to various individuals within their respective lists.

For instance: I possess a Json object detailing individuals:

"people": [
    {
        "id": 1,
        "name": "Tony Rogers",
    },
    {
        "id": 2,
        "name": "Steven Grant",
    },
    {
        "id": 3,
        "name": "Peter Wilson",
    },
]

Additionally, there exists a roster of skills that need to be associated with them:

"skills": [
    {
        "id": 1,
        "name": "Engineering",
        "personId": 1
    },
    {
        "id": 2,
        "name": "Painting",
        "personId": 2
    },
    {
        "id": 3,
        "name": "Chemistry",
        "personId": 3
    },
    {
        "id": 4,
        "name": "Physics",
        "personId": 1
    },
 ]

Navigating through both lists remains a bit uncertain for me. Ideally, I aim to attach a "skills" segment to each individual containing all of their relevant skills.

I toyed with the idea of:

people.forEach(function(person){
   skills.forEach(function(skill){

      if(skill.personId == person.id){ 
         person['skills'] = {"name" : skill.name};
      }
   });
});

However, this approach results in repetitive entries for an individual rather than consolidating their skills.

Answer №1

In order to store multiple skills, it is important to use an array type. Instead of simply assigning

person['skills'] = {"name" : skill.name};
, we should create an array and add the new skill object to it.

people.forEach(function(person){
   skills.forEach(function(skill){

      if(skill.personId == person.id){ 

         // Check if an array already exists for skills
         person['skills'] = person['skills'] || []; 

         // Add the skill object to the existing array
         person['skills'].push(skill.name);

      }
   });
});

Answer №2

Imagine you have 20 individuals each with 20 unique skills, that would result in a whopping total of 400 loops!

However, there is a more efficient way to handle this by utilizing just 2 loops:

var skillsByPerson = {};

skills.forEach(function(skill) {
  var personId = skill.personId;
  var personSkills = skillsByPerson[personId] || (skillsByPerson[personId] = []);

  personSkills.push({ name: skill.name });
});

people.forEach(function(person) {
  person.skills = skillsByPerson[person.id] || [];
});

If you're interested, you can check out the jsPerf test to see the performance comparison.

Answer №3

On each iteration, you are currently overwriting skills (specifically this part:

person['skills'] = {"name" : skill.name};
). Instead, what you should be doing is pushing a skill into an array of skills:

var individuals = [
  {"id": 1, "name": "Tony Rogers",}, 
  {"id": 2, "name": "Steven Grant",}, 
  {"id": 3, "name": "Peter Wilson",}];

var abilities = [{
  "id": 1,
  "name": "Engineering",
  "personId": 1
}, {
  "id": 2,
  "name": "Painting",
  "personId": 2
}, {
  "id": 3,
  "name": "Chemistry",
  "personId": 3
}, {
  "id": 4,
  "name": "Physics",
  "personId": 1
}, ]

individuals.forEach(function(person) {
  person['skills'] = []; // initialize empty skills array for each person
  abilities.forEach(function(skill) {

    if (skill.personId == person.id) {
      person['skills'].push({"name": skill.name}); // add the skill to the array
    }
  });
});

console.log(individuals);

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

Assertion using Node.js with Selenium WebDriver

I am currently working on implementing assertions for testing using selenium webdriver with node js. However, I am encountering an issue where it returns undefined when trying to assert the page title (which is the URL of the page). It seems like I may n ...

Filtering JSON data using the JQ tool for a lone JSON document

Within my data file lies: { "solr.jetty": { "org.eclipse.jetty.server.handler.DefaultHandler.requests": { "count": 432742, "meanRate": 0.1393530774422645, "1minRate": 0.1582358234691 ...

Trouble with HTTPS request in Android fragment

My app crashes and returns to the main activity whenever I try to use the search function with the Kitsu API in my fragment. I have observed through Logcat that no data is being fetched, but I am unable to determine what is causing the crash.The LogCat r ...

Modify the index in the creation of a json

I am trying to create a JSON object using the code below: var myJSONObject = []; var id = "1", value = "I'm a value !"; myJSONObject.push({id:value}); When I display this construction, it shows: [{"id":"I'm a value !"}] However, I want it to d ...

Decode JSON that may consist of either an array or a standalone item

My current challenge involves utilizing an API provided by a third-party that returns varying JSON results from the same endpoint based on the number of results received. For a single result, the response looks like this: { "data": { ... }, "metad ...

I consistently encounter the error message 'XRWebGLLayer is not defined no-undef' while implementing three.js within react.js to develop a WebXR application

Trying to implement WebXR with Three.js in a React project, encountering the error: 'XRWebGLLayer' is not defined no-undef for baseLayer: new XRWebGLLayer(session, gl) The code works fine in vanilla JavaScript but fails to compile in React. ...

Accessing JSON Data from a .NET Webmethod to Iterate through in AngularJS Directive

After extensive searching and seeking help, including referencing this SO answer: I have managed to retrieve data from a Webmethod and display it using {{data}} on the page. However, I am facing issues when trying to loop through the data, which consists ...

Display exclusively on indexes 0 and 3

Here is the code snippet I am working with: {(type === 'NEW') && ((index === 0) || (index === 3)) && <hr className={styles.hr}/>} I would like to combine these conditions into a single expression that w ...

What could be causing push() to malfunction within a loop?

Here is a snippet of my code: var cdata = []; d3.text("tests.info", function(text) { var data = d3.csv.parseRows(text); data.forEach(function(d) { cdata.push({key: d[0], values: []}); }); }); The code reads a CSV file, loops through each line ...

Implementing dynamic https URL embedding in AngularJS based on the user's browser location

When my webpage built with angularjs is launched using https, all urls within the page should also use https instead of the default http. Is it possible to make angularjs use either http or https based on the initial request? Here are some example embedd ...

Emitting events from a parent component to a child component

In the scenario mentioned above, using (click)="toggleSideBar()" in side-bar.component.ts does not close the sidebar. Is there a solution to this issue? ...

Storing user and message data with LocalStorage technology

Seeking advice on a straightforward approach to storing user data and messages. My idea is to use unique key values, such as random tokens (Ynjk_nkjSNKJN) for users, and real ids (1,2,3) for messages. Has anyone encountered this issue before? The goal is ...

Dividing image styles within css

I am trying to incorporate 4 arrow images into a CSS class (up, down, right, left). I started with a basic arrow css class: .arrow { background-repeat: no-repeat; background-position: center; } Next, I created subclasses like: .arrow .up { ...

When a cross-domain iframe is loaded in a private browser, it automatically logs the user out

I've been collaborating with a client to create a unique standalone website on a subdomain. They have requested that I utilize their API to initiate a straightforward post request when a user clicks a button. However, the client prefers the user to ut ...

Converting a file into JSON using PHP and it adds an additional line to the

I am relatively new to PHP and recently came across some code online that I modified to suit my needs. However, I noticed that sometimes it adds an extra value to the array. Everything works fine when the CSV looks like this: a:1 b:2 c:3 d:4 But ...

The issue with V-for not functioning arises when creating an array from an external JSON file during

Javascript: // List of Products const productsJSON = 'json/products.json'; // Component - Product Select app.component('product-select', { data() { return { selected: '', options: [] } }, ...

Yep, the condition within a nested object is true

Having an issue with conditional validation using yup. My goal is to make certain properties required for shipping when the checkbox is not toggled. I am utilizing yup's when feature, but I'm struggling to access the boolean value of sameShipping ...

What steps do I need to take to execute a browserify-ed application in NodeJS?

I have an interesting challenge on my hands - I need to modify a sizable JavaScript codebase to be compatible with NodeJS. The current code follows the CommonJS style and utilizes a gulp build process involving browserify and deamdify. While I am somewhat ...

Error message encountered: "Invalid JSON primitive - API call outcome"

I received the following data from an API call: [{ "generated_at": 1371490821, "status": "success", "station_id": 1, "station_name": "Hits Radio FM", "developer_id": 24, "count": 5, "refresh_url": "https://api.xxx.com/1/GET/now ...

SyntaxError: Unexpected '<' symbol found in JavaScript file while attempting to import it into an HTML document

This issue is really frustrating me In my public directory, there is an index.html file Previously, I had a newRelic script embedded within the HTML in script tags which was functioning properly Recently, I moved the script to a separate JavaScript file ...