looping through a collection of objects with partially distinct attributes

How can you iterate over an array of objects to retrieve the results of every previous game played? I encountered difficulties while attempting to iterate over non-existent values.

The desired result is an array structured like this:
newArr: [
    {
        "id": 1,
        team: 'rockets',
        record:{
             first: 'win',
             second: 'loss',
             thrid: 'loss'
             }
    },
    {
        "id": 2,
        team: 'raptors',
        record:{
             first: 'loss',
             }
    },
     ...
     ...

]
gamesPlayed: [
    {
        "id": 1,
        "team": "rockets",
        prevScore: [{
            value: {results: 'win'},
            prevScore: [{
                value: {results: 'loss'},
                prevScore: [{
                    value: {results: 'loss'},
                    prevScore: []
                }]
            }]
        }]
    },
    {
        "id": 2,
        "team": "raptors",
        prevScore: [{
            value: {results: 'loss'},
            prevScore: []
        }]
    },
    {
        "id": 3,
        "team": "hornets",
        prevScore: [{
            value: {results: 'win'},
            prevScore: [{
                value: {results: 'win'},
                prevScore: []
            }]
        }]
    },
    ...
]

Answer №1

When it comes to iterating through the teams map-function plays a crucial role.
Obtaining the id and team for the object from collectResults is quite straightforward. To retrieve the record, there is a function that takes a level parameter indicating how many results will be evaluated next for this team.
This function returns an empty object if prevScore is an empty array, otherwise, it extracts the first result into a new object. The function then recursively calls itself with level + 1 for the remaining results. Finally, the result-object from the current game along with the result-object from previous games are merged using Object.assign and returned.
You can extract the corresponding object entity-name (first, second, etc.) for the record by utilizing the LEVELS array with the specified level.

function collectResults(gamesPlayed) {
    let res = gamesPlayed.map( teamPlay => {
        let result = {
            id: teamPlay.id,
            team: teamPlay.team,
            record: getResults(teamPlay.prevScore, 0)
        }
        return result;
    });
    return res;
}

function getResults(prevScore, level) {
    const LEVELS = ['first', 'second', 'third', 'fourth'];
    if ( !prevScore.length ) 
        return {};
    else {
        let result= {};
        result[ LEVELS[level] ] = prevScore[0].value.results;
        let resultsPrevious = getResults(prevScore[0].prevScore, ++level);
   
        return Object.assign(result, resultsPrevious);
    }
}

let gamesPlayed = [
    {
        "id": 1,
        "team": "rockets",
        prevScore: [{
            value: {results: 'win'},
            prevScore: [{
                value: {results: 'loss'},
                prevScore: [{
                    value: {results: 'loss'},
                    prevScore: []
                }]
            }]
        }]
    },
    {
        "id": 2,
        "team": "raptors",
        prevScore: [{
            value: {results: 'loss'},
            prevScore: []
        }]
    },
    {
        "id": 3,
        "team": "hornets",
        prevScore: [{
            value: {results: 'win'},
            prevScore: [{
                value: {results: 'win'},
                prevScore: []
            }]
        }]
    }
];

console.log( collectResults(gamesPlayed) );

Answer №2

It may look a bit cluttered, but it gets the job done.

var data = [{
    "id": 1,
    "team": "rockets",
    prevScore: [{
      value: {
        results: 'win'
      },
      prevScore: [{
        value: {
          results: 'loss'
        },
        prevScore: [{
          value: {
            results: 'loss'
        }]
      }]
    }]
  },
  {
    "id": 2,
    "team": "raptors",
    prevScore: [{
      value: {
        results: 'loss'
      },
      prevScore: []
    }]
  }

];

var result = [];
var numbers = {
  1: "first",
  2: "second",
  3: "third",
  4: "fourth"
};

for (obj of data) {
  var index = 1;
  var oneGameResult = {
    "id": obj.id,
    "team": obj.team
  }
  var oneGameObj = {};
  buildResult(obj.prevScore, oneGameObj, index);

  oneGameResult["record"] = oneGameObj;
  result.push(oneGameResult);
}

console.log("result", result);

function buildResult(obj, oneGameObj, index) {

  var a = numbers[index];
  if (obj[0].prevScore && obj[0].prevScore.length > 0) {
    oneGameObj[a]=obj[0].value.results;
      
    index++;
    buildResult(obj[0].prevScore, oneGameObj, index);
  } else if (index == 1) {
    oneGameObj[a]=obj[0].value.results;
  }
}

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

Error encountered while converting JSON into an array in PHP index

Recently, I've been working with a JSON text that looks something like this: $text = '{"id": "12", "count": "1", "1": {"gkey": "g_c5218"}, "0": {"gkey": "g_4b4c6"}}'; My main goal is to convert this text into an array. Here's how I at ...

Tabulating Non-Prime Numbers

I am working on developing a method that will be able to determine and return the quantity of non-prime numbers present in an integer array. The existing method for marking prime numbers within an array is as follows (this portion does not require any mod ...

Sending information to a VueJS component

Hey there! I have a challenge in VueJS where I need to transfer Firebase Authentication user data (JSON) from the App.vue component to another component named Details.vue. The goal is to display the name of the logged-in user on Details.vue. In App.vue: ...

ngOptions failing to reflect changes when new objects are added to array

I am facing an issue with updating the view when a new object is pushed to an array that contains objects. It seems like the problem lies with $scope.$apply, but I'm not sure how to implement it properly. I attempted wrapping the push function in $sco ...

What can I do to ensure that the values of a vector in an array remain constant?

Is there a way to store vector data in an array without it being affected when the original vector values are changed? I inserted a vector into an array and when I modified its values, the corresponding values in the array also changed. const array10 = []; ...

What steps are needed to resolve the issue of inserting data into a database using Sequelize with Node Express and M

I am currently in the process of developing a straightforward registration form that will lead to additional CRUD operations using node.js. So far, I have set up the MySQL database and completed the modeling and connection with Sequelize. I have also desi ...

Passing a function a struct containing a pointer to an array in C

I need assistance with passing a pointer to an array, within a structure, into a callback function for an sqlite3 operation. It seems that my current understanding of pointers is causing issues as the logic I have implemented does not seem to work as expec ...

Running a PHP function embedded in a JavaScript script

I've gone through all the questions here but I'm still struggling to grasp this concept or make it work. My goal is to have a button that triggers a script to execute a php function. HTML: <button id="update_submit" type="button" onClick="m ...

Convert Screen Coordinates to World Coordinates with ThreeJS

While many people are interested in converting camera position to screen position, my question is how to achieve the opposite. Currently, I am trying to set the position of the "door" as a percentage of the screen, with the necessary calculations already ...

Encountering invalid JSON response while making an API request

Struggling to integrate GoToMeeting's API by sending a POST request to create a meeting. Currently, attempting to manually code the meeting body and send the necessary headers, but encountering an issue with invalid JSON error. Below is the code snipp ...

Tips for effectively handling requestAnimationFrame

I created a unique function that both scrambles and translates text. The functionality is smooth if you patiently wait for the animation to finish before moving the mouse over to other elements. However, if you try to rush through to the next one, the prev ...

Switch the background image of a div when hovering over a different div that is not its parent or sibling

I am in the process of building a dynamic portfolio on WordPress and I need some help with a specific functionality. At the top of my page, I have a large banner image, followed by individual thumbnails of my work below. What I want to achieve is the abili ...

Transferring an Object from one AngularJS Controller to Another

Currently delving into the world of AngularJS, I've encountered a seemingly trivial problem with no solution in sight. My issue lies in managing two lists/controllers created by a factory service. Specifically, I'm facing difficulties removing ...

Updating the current date at midnight or on the new day in JavaScript can be achieved using specific date and time

I have a web watch that is supposed to work 24/7 and display the digital time along with the current day. However, my issue is that when the time passes midnight, the current day does not update and I am forced to restart the entire application. I attempt ...

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. ...

Unbounded scrolling with Ionic

Currently, I am integrating Wordpress as the backend for my app and facing challenges in implementing infinite scroll due to issues with concatenating articles. To fetch the data, I have created a service using a factory: .factory('Worlds', fun ...

Is there a way to prevent Javascript from modifying styles when printing?

Is there a way to prevent JavaScript from affecting styling during printing? For example, if I'm using JavaScript to hide certain content but want that content to be visible when printed. I have hidden a div using JavaScript and now I'm trying ...

Having trouble muting the audio on my Vue audio player

I'm facing some challenges with muting the audio within my vue app. I have a list of songs that can be played, paused, shuffled, etc., but I can't seem to get the mute function working. Here's what I have in the JavaScript: mute() ...

Creating an animated background slide presentation

After creating a button group, I wanted the background of the previous or next button to move/slide to the selected one when the user clicks on it. I achieved this effect using pure CSS and simply adding or removing the 'active' class with jQuery ...

Describing how to assign multiple variables in a VUEX mutation

store.js import Vue from 'vue'; import Vuex from 'vuex'; import userStore from './user/userStore.js'; import VuexPersist from "vuex-persistedstate"; Vue.use(Vuex) const debug = process.env.NODE_ENV != ...