Adding key to multiple values in an object - javascript

I am looking to grab a string value from a text box and multiple values from a multiselect list and associate them where the string value is the key, and the multiple values from the drop down list are the values.
Here is the javascript code I have thus far:
var serviceName = document.getElementById('servicePackageText').value;
var sourceType = document.getElementById("multiple-checkboxes");
var groupName = serviceGroupName;
var serviceArray = new Array();
for (i = 0; i < sourceType.selectedOptions.length; i++) {
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
I want the format to look like this:
"Textbox value": [
multiselect_values,
multiselect_values,
multiselect_values,
multiselect_values
]
Any tips on how to proceed?

You need wrapper object, then it is easy. All you have to do is use [] property accessor to assign the object property.
I took some liberty with your code to make it simpler to rationalize:
var serviceName = "myDog"; //mock document.getElementById('servicePackageText').value;
var sourceType = [1, 2, 3, 4]; //mock document.getElementById("multiple-checkboxes");
var groupName = {};
groupName[serviceName] = sourceType; // <--- THE ANSWER
console.log(groupName);

Related

How to extract xml attribute and its value into json format using javascript

Seek for help to transform the xml to json. I got an input with this.
"<logRecord>
<logRecord>
<logRecord>
<class name="dto">
<logField fieldName="ID" oldValue=" " newValue="650"/>
<logField fieldName="submissionDt" oldValue="" newValue="03-12-2022"/>
</class>
</logRecord>
</logRecord>
</logRecord>"
and i want change to
[{fieldName : 'ID', oldValue : '' , newValue " '650'}.
{fieldName : 'submissionDt', oldValue : '' , newValue : '03-12-2022'}]
Is it possible? Thanks
I'm almost certain there is probably a better way of doing this, so I fully expect someone to come along and critique my attempt. However, the way I would achieve this (using the functions I know) would be using xpath to extract given values from the XML.
I've commented the code to try explain exactly what I'm doing but in essence, I'm looping over each <class> then looping each <logField> before finally looping over each of the attributes.
//First we'll take our (slightly more complex) XML input string
var xmlString = "<logRecord><logRecord><logRecord><class name=\"dto\"><logField fieldName=\"ID\" oldValue=\"\" newValue=\"650\" /><logField fieldName=\"submissionDt\" oldValue=\"\" newValue=\"03-12-2022\" /></class></logRecord><logRecord><class name=\"dto\"><logField fieldName=\"ID\" oldValue=\"\" newValue=\"123\" /><logField fieldName=\"submissionDt\" oldValue=\"\" newValue=\"19-12-2022\" /></class></logRecord></logRecord></logRecord>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
//Create a new XPathEvaluator
const evaluator = new XPathEvaluator();
//Evaluate given xpath to target every <class> found inside the XML
const classExpression = evaluator.createExpression('//class');
const classResult = classExpression.evaluate(xmlDoc, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
//Declare a final array
var arr = [];
//Loop each found instance of <class>
for (i=0; i<classResult.snapshotLength; i++) {
//Find all instances of <logField> inside of THIS <class>
const logFieldExpression = evaluator.createExpression('./logField');
const logFieldResult = logFieldExpression.evaluate(classResult.snapshotItem(i), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
//Declare an array to hold each of our <logField>s
var logFieldObj = [];
//Loop each <logField> inside of the <class>
for (j=0; j<logFieldResult.snapshotLength; j++) {
//Find all attributes for THIS <logField>
const attrEvaluator = evaluator.createExpression('./#*');
const attrResult = attrEvaluator.evaluate(logFieldResult.snapshotItem(j), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
//Declare a final object to hold each of the attributes fieldName, oldValue and newValue
var attrObj = {};
//Loop over each attribute
for (k=0; k<attrResult.snapshotLength; k++) {
//Add attribute as attributeName => attributeValue to our object
attrObj[attrResult.snapshotItem(k).localName] = attrResult.snapshotItem(k).textContent;
}
//Add our object to an array
logFieldObj.push(attrObj);
}
//Create the final resulting array
arr.push(logFieldObj);
}
console.log(arr);

How to add data to a 2-D map in Javascript

I mostly develop in Java, but I presently need to do some work using JavaScript.
I have data that I need to group by two dimensions: first by gender, and then by language. The object to be grouped comes like so:
var items =[ {
"language":"english",
"gender":"male",
...//twelve other fields
},
...
]
This is what I've tried:
var myMap = {};
for(var i=0; i<items.length;i++){
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myMap[_gender][_lang].push[item];
}
I assumed the above would work, but it’s not working. It keeps returning this error:
Uncaught TypeError: Cannot read property 'undefined' of undefined
Note: In Java, I would be creating a map of arrays.
One problem:
When you call myMap[_gender][_lang].push[item];, what you are actually doing is adding a key to the Object myMap, with the current value of _gender, and turning it into an Object, which you then create a new key for, set to the value of _lang. In addition, .push() is a function used with arrays, to add a new item onto the end of the array. If you want to add a new key and value to an Object, all you have to do is just call that key and assign it a value. Here's an example.
var obj = {
ex1 : 'example 1',
ex2 : 'example 2'
};
console.log(obj);
obj.ex3 = 'example 3';
console.log(obj);
//The code below will simply log 'undefined' in most consoles(it doesn't happen to do so in this snippet).
console.log(obj.ex4);
Here's my suggestion(assuming I correctly understand what you're trying to do):
var items = [{
"language":"english",
"gender":"male",
},
//...more below
];
myMap = [];
for(var i = 0; i < items.length; i++){
myArray = [];
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.push(myArray);
}
You are doing totally wrong. First of all myMap is object not an array so you can not use myMap.push().
You can achieve like this.
var items = {
"language":"english",
"gender":"male"
}
var myMap = {};
for(var key in items){
var myArray = [];
var _gender = items["gender"];
var _lang = items["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.item = myArray;
console.log(myMap);
}
for add 2-d array read this. 2-D Array in javascript

making JSON from string

I have a job to refractor strings to start using json so they can just pass json objects. So I have made array of names and then I'm trying to go through and make key and values but I'm getting an error in the console that it cant find x of no value. Can someone point me in the right direction?
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification', 'WorkQueue', 'TicketState',................ to long to post];
$().each(newName, function (key, value) {
key = newName[this];
value = newValues[this] = $('#' + key).val();
newArray = [key][value];
newArray = JSON.stringify(newArray);
alert(newArray);
$('.results').html(origArray[TicketNumber]);
});
I'm assuming you have "newValues" and "origArray" defined elsewhere?
In any case you'll need to at least adjust the following:
"$().each" should be $.each
"newArray" should be defined outside and you should use newArray[key] = value
you don't have a variable "TicketNumber" defined and so you should wrap "TicketNumber" in quotes
this is a reserved word so you shouldn't use it in "newName[this]" or "newValues[this]"
I suggest using a for loop instead of $.each() based on what you're trying to do inside.
https://msdn.microsoft.com/en-us/library/bb299886.aspx
var origArray = [];
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification'
];
for (var i = 0; i < newName.length - 1; i++) {
var object = {};
object[newName[i]] = newName[i];
object = JSON.stringify(object);
origArray.push(object);
}

cannot iterate through array and change value in JS

I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.

Create an array or object of elements with the same dynamic class

I currently the following jQuery collection / object:
[li.row-0, li.row-1, li.row-2, li-row-2, li.row-2, li.row-3]
Each class name is dynamically added to each element by a previous method. The only consistent part of the class name is row-. The number can be anywhere from 0 - ∞.
I want to create a new array or object of elements that are grouped by same dynamic class name:
[li.row-0]
[li.row-1]
[li.row-2, li.row-2, li.row-2, li.row-2]
[li.row-3]
The above is just a guess of the outcome, as I am not 100% sure how best to achieve this.
The aim is to be able to loop through .row-0, .row-1, .row-2, .row-3 and do something with the elements in each individual row.
I would do this :
var map = [].reduce.call(arr, function(map, v){
(map[v.className]||(map[v.className]=[])).push(v);
return map;
}, {});
var arr2 = [];
for (var className in map) arr2.push(map[className]);
The reduce builds a map having as keys the class names and with values the arrays of the elements having that class name.
I use [].reduce.call(arr, instead of arr.reduce( so that it works for standard arrays, jQuery collections, nodelists, etc.
Then the loop builds an array from that map. You might find the map more useful than the final array.
This shows you a general way of achieving this, though you're probably using elements rather than strings, but hopefully this will help
var tst = ['li.row-0','li.row-1','li.row-2','li.row-2','li.row-2','li.row-3'];
var grouped = [];
for(var i in tst)
{
var text = tst[i];
var num = text.replace('li.row-','');
if(!grouped[num]) grouped[num] = [];
grouped[num].push(text);
}
console.log(grouped);//[["li.row-0"], ["li.row-1"], ["li.row-2", "li.row-2", "li.row-2"], ["li.row-3"]]
Using elements:
var tst = [li.row-0,li.row-1,li.row-2,li.row-2,li.row-2,li.row-3];
var grouped = [];
for(var i in tst)
{
var text = tst[i].className;
var num = text.replace('row-','');
if(!grouped[num]) grouped[num] = [];
grouped[num].push(text);
}
console.log(grouped);//[["li.row-0"], ["li.row-1"], ["li.row-2", "li.row-2", "li.row-2"], ["li.row-3"]]
This method is more verbose and allows more complex grouping if need be (if other attributes come into play)
I would do something like the following:
var arr = ['li.row-0', 'li.row-1', 'li.row-2', 'li.row-2', 'li.row-2', 'li.row-3'];
var result = {};
$.each(arr, function (index, item) {
var ind = item.toString().split('row-')[1];
(result[ind] || (result[ind] = [])).push(item);
});
console.log(result);

Categories