Utilize SoundCloud API to generate user profiles according to their unique identification within the system

In my system, I have implemented a process that takes an array of SoundCloud user IDs. These IDs are then iterated through a series of SC.get functions to gather information about each user, such as their user ID, username, followings, and genre preference.

<script src="//connect.soundcloud.com/sdk.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>

<script>
    //Initializing the soundcloud API with client ID
SC.initialize({
    client_id: "54cb0ff94ff9313ef6ca4674e9fe3026"
});

var userIds = [9110252, 55829847, 145189041, 4184647, 225458844, 22557004, 109447512];
var userids = [];
var usernames = [];
var userFollowingsE = [];
var profile =[];
var ready = 0

for(u = 0; u < userIds.length; u++){
  var id = userIds[u];
  getUserData(id);

  function getUserData(userid){ 
  //**************************** USER ***************************//  
  SC.get("/users/"+id, function(user){
    userids.push(user.id);
    usernames.push(user.username);
  });

  //********************** USER/FOLLOWINGS **********************//
  SC.get('/users/'+id+'/followings',function(followings) {
    var userFollowings = [];
      for(i = 0; i < followings.collection.length; i++) { 
        userFollowings.push(followings.collection[i].username);                                         
    } 
    userFollowingsE.push(userFollowings);
      ready++
      if(ready >= userIds.length) onComplete();
    });
  }  
}

function onComplete(){
  console.log(usernames);
  console.log(userIds);
  console.log(userFollowingsE); 
}

var users = [ 
  { userid: this.userids,
    username: this.usernames,
    genre: this.genres,
    followings: this.followings,
  }
]

</script>
</body>

My goal is to associate the gathered information with each corresponding user in an object structure like:

var users = {
  user9110252: {
    userid = userid, 
    username = username,
    genrePref = genre
    followings = followings
  }
}//etc...

However, the output arrays from the system seem to change order each time and I suspect they are not correctly associated with each other.

I am seeking suggestions on how to resolve this issue and improve the system's functionality.

Answer №1

To achieve the desired format of the resulting array, it is recommended to construct the user Object as you iterate through the process instead of creating separate arrays and then consolidating them.

I have implemented a solution for this issue. Please execute the code snippet below to verify if it produces the anticipated outcome. Additionally, please note that I have excluded the genres due to their absence in the provided data.

//Initialize soundcloud API with client ID
SC.initialize({ client_id: "54cb0ff94ff9313ef6ca4674e9fe3026" });

var userIds = [9110252, 55829847, 145189041, 4184647, 225458844, 22557004, 109447512],
    users   = [];

for(var i=0; i<userIds.length; i++){ getUserData(userIds[i]); }

function getUserData(userid){
    // The user Object you'll be constructing
    var myUser = {};
    // Retrieve the information for this user
    SC.get("/users/"+userid, function(user){
        myUser.userid = user.id;
        myUser.username = user.username;
        // Obtain the followings for this user
        SC.get('/users/'+userid+'/followings',function(followings) {
            myUser.followings = followings.collection.map(function(user){
                return user.username;
            });
            // Add this user to the user list
            users.push(myUser);
            // Trigger the completion callback when all users have been fetched
            if(users.length == userIds.length){ onComplete(); }
        });
    });
}

function onComplete(){
    console.log(users);
    // Solely for demonstration purposes:
    document.body.innerHTML = '<pre>' + JSON.stringify(users,0,2) + '</pre>';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://connect.soundcloud.com/sdk.js"></script>

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

What steps should I take to ensure that my website can recall the most recent interaction conducted by the user?

Our website features a search form that allows users to look for items on the page. In addition, there is a separate form with checkboxes that enables users to narrow down their searches in hopes of reducing the number of results returned. For example, i ...

Enhance Your Website with Bootstrap 3.0 Affix

Looking to attach a right hand column to the top of the window as you scroll using Bootstrap 3.0 and 'affix' feature. Here is the HTML for the element: <div class="col-lg-4 right-hand-bar" data-spy="affix" data-offset-top="477"> This is ...

Ways to protect Ajax link requests

Picture this scenario: a user is trying to register on a website and is filling out a form. As the user fills in the form, jQuery continuously validates fields using regular expressions, checks if they are valid, etc. The email address serves as the prima ...

Altering the input field's content in response to a button click through JavaScript's addEventListener function

I am struggling to get the input text from a form field to change when a button is clicked using JavaScript. I can't seem to figure out why it isn't working correctly. Any assistance would be greatly appreciated. <!doctype html> & ...

Using SVG Mask to enhance shape Fill

I am having trouble achieving the desired effect of darkening the fill of objects based on a specified gradient. Instead, when the mask is applied over the fill, it actually lightens it. I suspect that this issue arises from the color blending method being ...

Guide to making a sliding animation appear when hovering over a menu using jQuery

I have noticed a common feature on many websites, but I am unsure of how to explain it. At times, there are sliding elements in the navigation, like an arrow under menu items that moves when the user hovers over different links. Here is an example of a s ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

AngularJS Interceptors for secure page management

I recently started working with AngularJS and I'm facing an issue with my interceptor that catches 401 errors from server responses. When a 401 status is detected, it triggers a "loginRequired" message broadcast and redirects to the login page. Howev ...

Result of utilizing Bootstrap Radio buttons

Looking at the HTML snippet below, I am trying to display two lines of radio buttons. However, when I click on a radio button in the first line and then proceed to click any radio button in the second line, the result of the radio button in the first line ...

What is the best way to connect my 'Projects' folder to app.js within a React application?

import "bootstrap/dist/css/bootstrap.min.css"; import Navbar from './components/Navbar'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './components/Home'; import Project ...

Develop a JavaScript function to declare variables

I am currently attempting to develop a small memory game where the time is multiplied by the number of moves made by the player. Upon completion of all pairs, a JavaScript function is executed: function finish() { stopCount(); var cnt1 = $("#cou ...

Determine the presence of a value within a specific column of an HTML table using jquery

When I input an ID number into a textbox, it shows me the corresponding location on a scale in another textbox. You can see an example of this functionality in action on this jsFiddle: http://jsfiddle.net/JoaoFelipePego/SdBBy/310/ If I enter a User ID num ...

Determine whether there are a minimum of two elements in the array that are larger than zero - JavaScript/Typescript

Looking for an efficient way to determine if there are at least two values greater than 0 in an array and return true? Otherwise, return false. Here's a hypothetical but incorrect attempt using the example: const x = [9, 1, 0]; const y = [0, 0, 0]; c ...

Form that adjusts input fields according to the selected input value

I am in need of creating a dynamic web form where users can select a category and based on their selection, new input fields will appear. I believe this involves using JavaScript, but my searches on GitHub and Stack Overflow have not yielded a suitable sol ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Error: Unable to access 'createInvite' property from undefined variable

Having trouble generating an invite to one of my guild's channels. Here is the code snippet I am using: const { Client } = require("discord.js"); const client = new Client({ intents: [] }); client.on("ready", async () => { ...

Issues with sending empty strings to an API in Vue Js

My code below is designed to update data using a Node Js REST API. The remaining field contains an equation using v-model=remaininginst to calculate and store the result in remaininginst. However, when I check the console.log, I am getting NaN empty data s ...

Find the string "s" within a div element aligned vertically, using Popper

Currently utilizing Popper from Material-UI <Popper id={"simplePopper"} open={true} style={{backgroundColor: 'red',opacity:'0.5',width:'100%',height:'100%'}}> <div style={{height:"100%", ...

Maximizing Efficiency: Using a Single Prototype-Instance Across Multiple HTML Pages

I have defined some Javascript "Classes" in separate files using the Prototype function as shown below: function Playlist(id, name){ this.id = id; this.name = name; } Playlist.prototype.getid = function(){return this.id;} Playlist.prototype.getn ...

Ways to determine if the user is either closing the browser or navigating to a different website

I am looking to set up session management in a manner where all sessions are expired or destroyed when the user closes the browser or tab. However, I would like to retain all the sessions if the user is navigating to another website. Is there a way to ac ...