To loop within array of arrays - javascript

In my below code Im am not able to fetch data within array
var str = "Service1|USER_ID, Service1|PASSWORD"
var str_array = str.split(',');
console.log(str_array)
for(var i = 0; i < str_array.length; i++)
{
str_array[i] = str_array[i].split('|');
}
console.log(str_array)
This is the response from above code
/* [ [ 'Service1', 'USER_ID' ],
[ 'Service1', 'PASSWORD' ] ]*/
I want response to be in two different array like below
var array1 = ['Service1']
var array2 = ['USER_ID','PASSWORD']
Any help on this will be really helpful

Since you're on Node, you can do this:
var str = "Service1|USER_ID, Service1|PASSWORD";
var result = str.split(',').reduce(function(collected,splitByComma){
var splitData = splitByComma.split('|');
var key = splitData[0].replace(/\s+/gi,''); //Might want to improve this "trim"
var data = splitData[1];
if(!collected.hasOwnProperty(key)) collected[key] = [];
collected[key].push(data);
return collected;
},{});
console.log(JSON.stringify(result)); //{"Service1":["USER_ID","PASSWORD"]}
//result.Service1[0] == USER_ID
//result.Service1[1] == PASSWORD
It's not wise to place stuff in separate places. You could have them under an object key though. If service name is variable, then you could do:
var serviceName = "Service1";
result[serviceName][0] == USER_ID
result[serviceName][1] == PASSWORD

As I have understand your question, you will want an array associated with each service key, to be able to do
services.service1
and get ['username', 'password' ] ?
If so, here's a solution:
var str = "Service1|USER_ID, Service1|PASSWORD".replace(', ', ',').split(','), //[ 'Service1|USER_ID', 'Service1|PASSWORD' ]
out = {};
str.forEach(function(element){
var key, value;
element = element.split('|');
key = element[0].trim();
value = element[1].trim();
out[key] = out[key] || []; // ensures we can push the value into an array
out[key].push(value);
});
console.log(out); //{ Service1: [ 'USER_ID', 'PASSWORD' ] }

We can have a simple Regex solution
var res = "Service1|USER_ID, Service1|PASSWORD".split(/[\|,]/g);
var ar1 = [], ar2 = [];
res.forEach(function(em,i){
if(i%2==0) {
if(ar1.indexOf(em.trim())<0){
ar1.push(em.trim());
}
} else {
ar2.push(em.trim());
}
});
//ar1 and ar2 will contain expected results

Related

How can I use number as key?

I have ids like as numbers 374,242,435
I want to use this as key of hash for the object.
var json = [];
ids = [374,242,435];
for(let i in ids) {
var id = ids[i];
json[id] = []; // it makes 372 array!!!
json[id]['name'] = name;
json[id]['color'] = color;
}
Can I make object using number as key????
This is my silly mistake
I just changed var json = []; -> var json = {}; it works.
and thank you for your comments.
let json = {};
let ids = [374,242,435];
for(let i in ids) {
let id = ids[i];
json[id] = {
name: 'some name',
color: '#ff0000'
};
}
EDIT: A better version
let json = {};
let ids = [374,242,435];
ids.forEach((id) => {
json[id] = {
name: 'some name',
color: '#ff0000'
};
});
You can use Map to store key-value pair. In Map, key will not just be string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var json = {};
var ids = [374,242,435];
for(const i of ids) {
json[i] : {
name : 'name',
color : '#colorcode'
}
}

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 = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
];
(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
}
var list = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
];
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": [
"john#yahoo.com",
"josh#yahoo.com"
],
"gmail.com": [
"rami#gmail.com",
"bale#gmail.com"
]
}
*/
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 = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
]
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.
You can simply push the values in the array if the key is found in object otherwise add the array
var list = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
];
(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>
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 = [
"john#yahoo.com", "rami#gmail.com",
"josh#yahoo.com", "bale#gmail.com"
];
(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>
Array.prototype.reduce is typically used to translate array data to object form.
See below for a practical example 👇
// Emails.
const emailAddresses = ["bale#gmail.com", "john#yahoo.com", "rami#gmail.com","josh#yahoo.com"]
// 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)

How can I capture a hash to Object in functional JavaScript?

I'm writing a piece of code in JavaScript for modern browser. I'm not using lodash or underscore as we want to keep the library as small as possible.
For example,
If the url comes like this. http://something.com/#hash=value
And the app is configured to capture key hash then the result would be this. Nothing fancy. I was just wondering if there's a better way or simple way to do this.
{
'hash': 'value'
}
The code
var config = Object.assign({}, {
capturedHashParams: ['hash']
});
var hashValue = '#hash=value1'.substr(1);
var capturedHashParams = {};
if (config.capturedHashParams && Array.isArray(config.capturedHashParams)) {
var splitedHash = hashValue.split('=');
if (splitedHash.length > 0) {
var key = splitedHash[0] || '';
var value = splitedHash[1] || '';
if (key && value) {
config.capturedHashParams.forEach(function(hp) {
if (hp.toLowerCase().indexOf(key.toLowerCase()) > -1) {
capturedHashParams[key] = value;
}
});
}
}
}
console.log(capturedHashParams);
https://jsfiddle.net/c92p0rfm/2/
i think you are watching for something like this:
var output = [];
var hashString = window.location.hash;
var hashArray = hash.split('&');
for(var index = 0; index < hashArray.length; index++){
var text = hashArray[index];
var tempArray= text.split('=');
var object = {
id: tempArray[0],
value: tempArray[1]
};
output[index] = object;
}
now output looks like this:
[
{
id: "hash",
value: "value"
}
]
Your question is somewhat ambiguous. It appears that you want to extract key/value pairs from an url hash and return as a JavaScript object. I am bit uncertain about whether you want to extract all key/value pairs or only those provided in a config object. I am also a bit uncertain as to whether you want a solution within a strict functional programming paradigm, or just a plain solution with a small code footprint. I will assume the latter.
A straightforward approach to capture all key/value pairs:
var url = 'http://something.com/#hash=value&anotherHash=value';
//extract key=value pairs from url
var params = url.split('#').pop().split('&');
//assign to data object
for(var data = {}, i = 0, temp; i < params.length; i++){
// extract array [key, value]
temp = params[i].split('=');
// assign to data object
data[temp[0]] = temp[1];
}
console.log(data);
A more compact solution to do the same with .reduce():
var url = 'http://something.com/#hash=value&anotherHash=value';
var data = url
.split('#')
.pop()
.split('&')
.reduce(function(obj, keyval){
keyval = keyval.split('=');
obj[keyval[0]] = keyval[1];
return obj;
}, {});
console.log(data)
If you want to configure which keys to extract:
var url = 'http://something.com/#hash=value&anotherHash=value&notThisHash=value';
//config object
var keysToCapture = [
'hash',
'anotherHash'
];
var data = url
.split('#')
.pop()
.split('&')
.reduce(function(obj, keyval){
keyval = keyval.split('=');
if(keysToCapture.indexOf(keyval[0]) > -1){
obj[keyval[0]] = keyval[1];
}
return obj;
}, {});
console.log(data)
Which you could capture in a reusable function like this:
function extractParamsObject(url, keysToCapture){
return url
.split('#')
.pop() //hash/fragment: everything after the last #
.split('&')
.reduce(function(obj, keyval){
keyval = keyval.split('=');
if(keysToCapture.indexOf(keyval[0]) > -1){
obj[keyval[0]] = keyval[1];
}
return obj;
}, {});
}
console.log(extractParamsObject(
'http://something.com/#hash=value&anotherHash=value&notThisHash=value',
['hash', 'anotherHash']
));

how to get values from an array in javascript?

let the array be
var array=
[
"me=Salman","Profession=student","class=highschool"
]
How do I extract the value of 'me' here?
Try this:
var result = '';
for(var values in array){
if(values.indexOf('me=') !== -1 ){
result = values.split('=')[1];
break;
}
}
You will need to search the array for your desired portion of the string, then remove what you searched for from the indicated string.
var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var findMatch = "me=";
var foundString = "Did not find a match for '"+findMatch+"'.";
var i = 0;
for (i = 0; i<array.length; i++) //search the array
{
if(array[i].indexOf(findMatch) != -1) // if a match is found
{
foundString = array[i]; //set current index to foundString
foundString = foundString.substring(findMatch.length, array[i].length); //remove 'me=' from found string
}
}
Try this:
var a = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var result = a.filter(function(e){return /me=/.test(e);})[0]; // Find element in array
result = result.length ? result.split('=').pop() : null; // Get value
Or function:
var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];
function getVal(arr, key){
var reg = new RegExp(key + '=');
var result = arr.filter(function(e){ return reg.test(e)})[0];
return result.length ? result.split('=').pop() : null;
}
console.log( getMe(array, 'me') );

How to convert an array of objects into a mapped object in JavaScript?

How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});

Categories