Put the values into an array format for each key within an object using JavaScript

I am attempting to transform an array containing email addresses into an object. How can I insert values in the value array for a single key?

var list = [
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6903060107291008010606470a0604">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a584b47436a4d474b434604494547">[email protected]</a>",
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f05001c072f160e070000410c0002">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abc9cac7ceebccc6cac2c785c8c4c6">[email protected]</a>"
];

(function() {
  var obj1 = {};
  for (var a = 0, b = list.length; b > a; a++) {
    var str = list[a].split("@");
    var arr = [];
    arr.push(str[0]);
    if (!(str[1] in obj1)) {
      obj1[str[1]] = []; //arr.push(str[0])];
    }

    Object.values(obj1[str[1]]).push(str[0])

  };
  console.log(obj1);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
expected result

    {
    "gmail.com" : ["a","b","c"],
    "yahoo.com" : ["de","e","f"]
    }

I would also like to include this as well

    {
    "gmail.com" : [3],//1+1+1
    "yahoo.com" : [4]//1+1+1+1
    }

Answer №1

var list = [
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d272225230d342c252222632e2220">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a4b7bbbf96b1bbb7bfbaf8b5b9bb">[email protected]</a>",
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f75706c775f667e777070317c7072">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbb9bab7be9bbcb6bab2b7f5b8b4b6">[email protected]</a>"
];
obj = {};
list.map(x => x.split('@')[1]).forEach(x => obj[x] = [])
list.forEach(email => obj[email.split('@')[1]].push(email))
console.log(obj)
/*
{
  "yahoo.com": [
"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adc7c2c5c3edd4cc67173636317f87cac0cdcecedececfc0cdc8afe4e8ea"></a>",
"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c2c7dbc0e8d15d76737c6f79726a69766978787977"></a>"
  ],
  "gmail.com": [
"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccbeada1a58caba1ad278984683ade3ede04ca7aba9958cceaca0"></a>",
"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1270737e7752757f737b7e3c717d7f"></a>"
  ]
}
*/

Explanation: A blank object obj was created. The code then iterates over list to extract all the domains using

list.map(x => x.split('@')[1])
.

The object is structured as follows:

{ 'yahoo.com': [], 'gmail.com': [] }

Following that, another iteration over the list adds the email if the domain matches, resulting in the final object.

Edit: Alternatively, it can be achieved with a single iteration like this:

var list = [
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80eaefe8eec0f9e1e8efefaee3efed">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="285a494541684f45494144064b4745">[email protected]</a>",
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2842475b40685149404747064b4745">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99fbf8f5fcd9fef4f8f0f5b7faf6f4">[email protected]</a>"
]
obj = {}
list.forEach(email => {
  let domain = email.split('@')[1]
  if (!obj[domain]) obj[domain] = []
  if (obj[domain].indexOf(email) < 0) obj[domain].push(email)
})
console.log(obj)

This version iterates over the list, extracts the domain, creates the key with [] if it doesn't exist, and then appends the email accordingly while eliminating duplicates.

Answer №2

To easily populate the array with values, check if the key exists in the object before adding the array.

var list = [
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e040106002e170f060101400d0103">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dffece0e4cdeae0ece4e1a3eee2e0">[email protected]</a>",
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43292c302b033a222b2b2c6c6d7c202c2e">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3b1b2bfb693b4beb2babffdb0bcbe">[email protected]</a>"
];

(function() {
  var obj1 = {};
  for (var a = 0; a < list.length;  a++) {
    var str = list[a].split("@");
    if(obj1[str[1]]) {
        obj1[str[1]].push(list[a])
    } else {
        obj1[str[1]] = [list[a]]; //arr.push(str[0])];
    }
  };
  console.log(obj1);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №3

Just a small adjustment needed in your code to fix the bug. Update this line:

Object.values(obj1[str[1]]).push(str[0])

to

obj1[str[1]].push(list[a]);

After making this change, it should work correctly.

var list = [
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fefbfcfad4edf5fcfbfbbaf7fbf9">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7f6c60644d6a606c6461236e6260">[email protected]</a>",
  "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3999c809bb38a929b9c9cdd909c9e">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1c3c0cdc4e1c6ccc0c8cd8fc2cecc">[email protected]</a>"
];

(function() {
  var obj1 = {};
  for (var a = 0, b = list.length; b > a; a++) {
    var str = list[a].split("@");
    var arr = [];
    arr.push(str[0]);
    if (!(str[1] in obj1)) {
      obj1[str[1]] = []; //arr.push(str[0])];
    }

    obj1[str[1]].push(list[a]);

  };
  console.log(obj1);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №4

Array.prototype.reduce is commonly used to convert data from an array to an object.

Check out the example below for a practical demonstration 👇

// Phone Numbers.
const phoneNumbers = ["123-456-7890", "987-654-3210", "555-1212"]

// Format as Objects.
const formatAsObjects = numbers => numbers.reduce((acc, number, index) => {
  acc[`Entry ${index + 1}`] = { phoneNumber: number }
  return acc
}, {})

// Result.
const result = formatAsObjects(phoneNumbers)

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

Creating a sticky menu in a column using affix with a CSS bootstrap list-group

My goal is to develop a sticky menu utilizing CSS Bootstrap affix and the list-group menu. I have successfully implemented most of it, except for one issue when the user scrolls down. Upon scrolling down, the menu expands to fill the entire width of the ...

Clicking a button triggers a call to an API endpoint, resulting in a message being displayed on the client side

I am struggling with a simple school assignment that involves creating an API endpoint in Node.JS to respond to a GET request. The goal is that when clicking a button in the HTML file, the API should be called and display the message "Hello World" along wi ...

Transferring an array from PHP to jQuery

How can I pass an array from PHP to jQuery within the same file? I have an array named $array2 with data that I want to use to create a graph. The code below is currently using predefined chartData, but I would like to use a variable from my PHP script i ...

Encapsulate ng-style within quotation marks

I am trying to hide a span if the value of filters[*index*] is empty. var span = "<span ng-style='{ 'display': filters[" + filterIndex + "] == '' ? 'none' : 'inline-block' }'></span>" cell.html ...

Issue with Videogular: hh:mm:ss Date filter not functioning properly

I am currently working on integrating Videogular into my audio player application. Below are the settings provided in the example code on this particular page: <vg-time-display>{{ currentTime | date:'mm:ss' }}</vg-time-display> ...

JavaScript - organizing, transforming, and combining arrays of objects containing arrays within them

Greetings, I am struggling to achieve the following outcome: {"2002":[1,2,3...]}, {"2003":[1,2,3,4...]}, ... Below is a brief example of the data I have: { "Year": "28-01-2020", "numbers": [10, 12, 20, 32, 35, 37] }, { "Year": "03-10-2019", "numbers": ...

The setInterval function appears to be undefined despite being explicitly defined earlier

Within the HEAD section of my code, I have defined a function like so: <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"> function live() { $.get("http://mydomain.com/script.php", function(data){ var timer ...

Top approach for accessing data through a Factory function in Angular

Seeking guidance on the most effective method for fetching data from a local JSON file and managing the response. The plethora of options found on Stack Overflow has left me with conflicting thoughts, as different approaches yield similar results without c ...

What could be causing the issue with local storage in React JS not functioning in real time?

I tried implementing this code from a blog post to use local storage with React, but I'm facing an issue where it doesn't update in real-time after refreshing. I believe using the effect hook can potentially solve this, but I'm struggling to ...

Remove an item with AngularJS

I have a JSON file that contains data which I am able to display using AngularJS. The information is presented in rows with checkboxes and a Delete button. My goal is to remove the data from both the display and the JSON file. To delete, simply click on th ...

Adjust the Placement of Images in Relation to Mouse Movements

Is there a way to creatively animate the positions of images or background images based on mouse movement? Let's take Github, for instance: https://github.com/thispagedoesntexist The 404 page on Github is truly impressive. I aim to captivate my use ...

JavaScript: Dynamic animation of a DIV element based on conditions

I am looking to create an animation for a DIV layer when another div is clicked. However, I only want the animation to play if the DIV layer has not been animated yet. My initial thought was to check the height value, as I am animating the height of the d ...

Enhance the database with partial updates using the patch method in Django Rest Framework

I have a model called CustomUser that extends the AbstractUser class. class CustomUser(AbstractUser): detail = models.JSONField(default=dict) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=Tr ...

PHP AJAX for a Multi-Select Form

Hi there, I'm having some trouble with PHP AJAX to display the result in a select field. My goal is to have the second select field appear after choosing an option in the first one, and then load the third select field when selecting an option in the ...

Filtering nested JSON arrays with the help of Knockout JS

I have been experimenting with filtering a nested JSON array using Knockout js. Let me share how my JSON data is structured: { "groups": [{ "name": "Category1", "items": [{ "question": "Question1", "answer": "Answer1" }] }, { ...

Retrieving a particular object/item based on its id using Firebase

Currently in the process of developing a small web app using Firebase and React, I am encountering difficulty retrieving specific items from Firebase on the client-side of React. In traditional JavaScript, a basic fetch request might appear as follows: ...

JavaScript Audio working on local machine but not on server due to HTML5 compatibility issues

For my project, I am utilizing audio and Javascript in the following way: To start, I populate an array with audio files: var soundArray = new Array(); for (i=0; i<6; i++) { soundArray[i] = new Audio('sounds/sound_' + i + audioExt); ...

Adjusting ES2015 Map to accommodate the expected functionality

Exploring the capabilities of ES2015 Maps has been quite exciting, as I'm starting to see its potential. However, I've encountered a use case that has me stumped on whether Maps can handle it. Let's take a look at my class: class A { ...

Storing arrays within a document in MongoDB

Initially, I designed a database schema for events that looked like this: { events: { eventid : { userid : availability } } This method worked well for data upserts since the ke ...

"Using Jquery, Ajax, and PHP to handle a two-dimensional checkbox

I am working with checkbox groups in my form, structured like this: <?php foreach ($group as $gid){ ?> <div class="option"> <input type="checkbox" name="group[<?php echo $gid->id; ?>]" value="1" /> <input type="checkbox" name ...