Hemant
Hemant

Reputation: 401

insert values in array format for key in object in JavaScript

I am trying to convert an array(with email addresses) in to object. How to insert values in value array for one key?

var list = [
  "[email protected]", "[email protected]",
  "[email protected]", "[email protected]"
];

(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 output

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

I also want to add like

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

Upvotes: 0

Views: 63

Answers (4)

Arman Charan
Arman Charan

Reputation: 5797

Array.prototype.reduce is typically used to translate array data to object form.

See below for a practical example 👇

// Emails.
const emailAddresses = ["[email protected]", "[email protected]", "[email protected]","[email protected]"]

// Group By Domain.
const groupByDomain = addresses => addresses.reduce((acc, email) => {
  const [prefix, domain] = email.split(/@/)
  const exists = acc[domain]
  if (exists) acc[domain].push(email)
  else acc[domain] = [email]
  return acc
}, {})

// Output.
const output = groupByDomain(emailAddresses)

// Proof.
console.log(output)

Upvotes: 0

kiddorails
kiddorails

Reputation: 13014

var list = [
  "[email protected]", "[email protected]",
  "[email protected]", "[email protected]"
];
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": [
"[email protected]",
"[email protected]"
  ],
  "gmail.com": [
"[email protected]",
"[email protected]"
  ]
}
*/

Explanation: Created a blank object obj. Then I iterated on list and retrieved all the domains by list.map(x => x.split('@')[1]).

With domains in hand, I setup-ed the object to have the structure { 'yahoo.com': [], 'gmail.com': [] }

Then I iterated on list again and added the email if domain contained the corresponding part, giving resultant object.

Edit: It can also be done in single iteration this way:

var list = [
  "[email protected]", "[email protected]",
  "[email protected]", "[email protected]"
]
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)

Here, I'm iterating on list, extracting the domain, setting up the key with [] if it doens't exist and then pushing the email into that. It also makes sure that no duplicate emails are pushed.

Upvotes: 1

amrender singh
amrender singh

Reputation: 8239

Your code is almost correct, there is just a minor bug, change your line:

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

To

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

And it works fine.

var list = [
  "[email protected]", "[email protected]",
  "[email protected]", "[email protected]"
];

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

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281686

You can simply push the values in the array if the key is found in object otherwise add the array

var list = [
  "[email protected]", "[email protected]",
  "[email protected]", "[email protected]"
];

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

Upvotes: 0

Related Questions