Creating a dynamic multidimensional array or object in AngularJS: tips and tricks

Below is the code snippet where I am attempting to dynamically construct an associative array in angularJs:

  $scope.details = {"profilesFound": [
    "https: //twitter.com/alexandreagular",
    "https: //twitter.com/?profile_id=46130006",
    "https: //facebook.com/1290628666",
    "https: //twitter.com/intent/user?user_id=84326171",
    "https: //www.linkedin.com/in/alex",
    "https: //www.linkedin.com/in/alexandreagular",
    "https: //www.facebook.com/alexandre.agular",
    "https: //www.facebook.com/alexandre"
  ]};

  $scope.socialProfiles = [];
  var spLength = $scope.details.profilesFound.length;

  for(var i=0;i<spLength;i++){
    var url = $scope.details.profilesFound[i];
    var domain = url.replace('.com','').replace('http://www.','').replace('https://www.','').replace('http://','').replace('https://','').split(/[/?#]/)[0];
    $scope.socialProfiles[domain]=url;
  }

My desired array construction is as follows:

 "profilesFound":{
"facebook":[
  "https://facebook.com/1290628666",
  "https://www.facebook.com/alexandre.agular"
],
"twitter":[
  "https: //twitter.com/alexandreagular",
  "https: //twitter.com/?profile_id=46130006",
  "https: //twitter.com/intent/user?user_id=84326171"
],
"linkedin":[
  "https: //linkedin.com/1290628666",
  "https: //www.linkedin.com/alexandre.agular"
]

}

However, the resulting output I am getting is:

[twitter: "https://twitter.com/intent/user?user_id=84326171", facebook: "https://www.facebook.com/alexandre.agular", linkedin: "https://www.linkedin.com/in/alexandreagular"]

Any solutions or suggestions would be greatly appreciated. Thank you.

Answer №1

Make sure to update $scope.socialProfiles[domain] by appending to it for each new website, not reassigning it.

Instead of

$scope.socialProfiles[domain]=url;

Consider using

if(!$scope.socialProfiles[domain])
    $scope.socialProfiles[domain] = []

$scope.socialProfiles[domain].push(url);

Answer №2

$scope.details = {
    profilesFound: [
      "https://twitter.com/johndoe",
      "https://twitter.com/?profile_id=12345678",
      "https://facebook.com/987654321",
      "https://twitter.com/intent/user?user_id=87654321",
      "https://www.linkedin.com/in/john",
      "https://www.linkedin.com/in/johndoe",
      "https://www.facebook.com/johndoe",
      "https://www.facebook.com/john"
    ]
  },
  $scope.socialProfiles = {};

$scope.details.profilesFound.forEach(function(profile) {
  var domain = profile.replace('.com', '').replace('http://www.', '').replace('https://www.', '').replace('http://', '').replace('https://', '').split(/[/?#]/)[0];
    $scope.socialProfiles[domain] = $scope.socialProfiles[domain] || [];
  $scope.socialProfiles[domain].push(profile);
});

Answer №3

Give this a shot:

$scope.data = {"accounts": [
    "https://twitter.com/alexandreagular",
    "https://twitter.com/?profile_id=46130006",
    "https://facebook.com/1290628666",
    "https://twitter.com/intent/user?user_id=84326171",
    "https://www.linkedin.com/in/alex",
    "https://www.linkedin.com/in/alexandreagular",
    "https://www.facebook.com/alexandre.agular",
    "https://www.facebook.com/alexandre"
  ]};
    $scope.object = {};
   $scope.data.accounts.forEach(function (link, index) {
    var base = link.split('.com');
    var site = base[0].replace('http://www.', '').replace('https://www.','').replace('http://', '').replace('https://','');

    if(typeof $scope.object[site] !== 'undefined') $scope.object[site].push(link);

    else $scope.object[site] = [link];

    console.log($scope.object);
   });

Check out this live demo

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

Exploring the versatility of orderBy and filter in handling cross-referenced content across multiple JSON objects

Is there a way to filter and search for the item name when the item details are sourced from another JSON object? Demo: http://codepen.io/anon/pen/GjAxKX While the rest of the filtering and ordering functionalities are functioning correctly, I am struggl ...

Selector that targets an attribute in the beginning of its value [name^=value]

When trying to match input fields by name, I encountered a challenge. The names consist of a base name plus square brackets, which the PHP interpreter converts into arrays. According to the jQuery API, the suggested selector is as follows: ":input[name^=f ...

Audio transition on hover over image

I'm currently designing a website and I have an image depicting a house with windows. I would like to create an interactive element where the face of Goldilocks pops up in one of the windows on mouseover, accompanied by sound. I envision the face movi ...

Error: The function Stripe.customers.cancel is not recognized in Stripe version 14.18.0

When executing Cypress tests that involve calling a cleanup function to remove users in Stripe, I encounter the following error: Body: { "status": 500, "message": "Error while cleaning the stripe test data", "error" ...

How can you deactivate all form elements in HTML except for the Submit button?

Is there a method available to automatically deactivate all form elements except the submit button as soon as the form loads? This would entail pre-loading data from the backend onto a JSP page while restricting user access for editing. Users will only be ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

What is the best way to access and manipulate data stored in a Firestore map using React?

In my Firestore database, I have a field with map-like data: coordinates:{_01:"copper",_02:"gold",_03:"iron"} When viewing this database in the Firestore admin panel, it appears like this: pic However, when attempting to list items using the following c ...

Sorting arrays in javascript

My JavaScript array is structured like this: var data_tab = [[1,id_1001],[4,id_1004],[3,id_1003],[2,id_1002],[5,id_1005]] I am looking to organize and sort them based on the first value in each pair: 1,id_1001 2,id_1002 3,id_1003 4,id_1004 5,id_1005 ...

Using nodeJS to showcase content on a web page

I'm relatively new to NodeJS, and I am trying to figure out if there is a way to utilize NodeJS similar to JavaScript. My goal is to retrieve data from a database and display it within a div on my index.html page. When attempting to use querySelector, ...

Having trouble with updating React state? The useEffect hook runs when attempting to change the state, but it seems to have the

Having worked with useEffect and its ability to trigger after a state variable has been updated, I am well-versed in its functionality. I'm currently drafting this post on my phone while away from home. Here's the setup I have: const [dateValue ...

Is there a method to track the number of active onSnapshot listeners from Firestore in my application?

In my app, I am implementing a feature that dynamically removes query onSnapshot listeners and replaces them with new ones. To ensure that resources are properly freed up, I need to test the effectiveness of the unsubscribe function. Unfortunately, I do n ...

Steps for converting a window to a PDF file rather than an XPS file

Whenever I attempt to print the contents of my HTML page using window.print(), it always creates an XPS file. However, what I really need is for it to generate a PDF file instead. Any assistance would be greatly appreciated. Thank you! ...

Form an array using the values that are returned

As I iterate through an object and extract elements, my console.log displays: ["item 1"] ["item 2"] ["item 3"] and so on. All I want is to create a new array formatted like this: ["item 1","item 2","item 3"]; ...

Why must the sidebar be displayed horizontally on the smartphone screen?

I've been struggling to make the sidebar menu on my smartphone display horizontally with icons at the top and text at the bottom. I've tried using flex and other methods, but it still doesn't work sideways. Am I missing something? const s ...

"Utilizing Vue Mixins on a global scale, but restricting their usage to local components

Is there a way to use a mixin in multiple components without having to constantly import and declare it? I've tried connecting the mixin object to a global variable using vue.prototype, but mixins are added to components before globals are accessible. ...

Determine the viral coefficient based on the sharing platform being used, whether it is Facebook or Twitter

Traditionally, the viral coefficient is measured through email addresses. For example, if a current user [email protected] invites 10 people via email, you can track how many signed up and calculate the viral coefficient based on that. But what if th ...

Verify whether a specific value is present within a nested array in MongoDB

Looking to verify whether a value sent in a request already exists within an array associated with a particular User. The data structure is as follows: { "_id": "63233972df0f14076e027106", "firstName": "mako" ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Error: The MUI Popper Component constantly closes when re-rendering due to props issue

I have been exploring how to structure a component incorporating MUI's Popover component, especially when dealing with dynamic props being passed to a controlled Slider component inside the Popover as well as the anchor element being updated dynamical ...

Is there a way to enable hover functionality on mobile devices? I wish for the hover effect seen on desktop to be triggered automatically on mobile devices

I attempted to implement @media (hover: hover) without success. In my design, I have three images in a row that reveal a text overlay when hovered over with a mouse. However, the issue arises when I try to switch to a mobile view, as the images remain un ...