create an object array from a form in javascript - javascript

This is the kind of ptoblem that in python i take two minutes to solve but in js or jquery i fight for hours...
i have a form and i need to elaborate the data client-side.
With :
var serializedData = $('form#ae_form_grid').serialize()
i obtain this:
"id=13&quantita_gen_grid=2&prezzo_gen_grid=120&sconto_gen_grid=&prezzo-15=120&quantita-15=4&sconto-15=&selezionato-16=on&prezzo-16=120&quantita-16=2&sconto-16=&prezzo-14=120&quantita-14=2&sconto-14=&selezionato-17=on&prezzo-17=122&quantita-17=3&sconto-17="
i need to create an object array possibly with this from:
["16":{ prezzo:120,quantita:2,sconto:""},"17":{prezzo:122,quantita:3,sconto:""}]
16 and 17 are from the keys with "selezionato" in the name and prezzo, quantita... are the -16 and -17 ..
i tried with:
$.each(serializedData.split('&'), function (index, elem) {
var vals = elem.split('=');
var selected = vals[0].split("-");
if (selected[0] == "selezionato") {
sel.push(selected[1])
}
})
and i have an array of the right key but i can go further.
thanks
F

Here you are:
var input = "id=13&quantita_gen_grid=2&prezzo_gen_grid=120&sconto_gen_grid=&prezzo-15=120&quantita-15=4&sconto-15=&selezionato-16=on&prezzo-16=120&quantita-16=2&sconto-16=&prezzo-14=120&quantita-14=2&sconto-14=&selezionato-17=on&prezzo-17=122&quantita-17=3&sconto-17=";
//["16":{ prezzo:120,quantita:2,sconto:""},"17":{prezzo:122,quantita:3,sconto:""}
var array = input.split('&');
var attributes = ['prezzo', 'quantita', 'sconto'];
var keys = $.map(array, function(value) {
var string = value.split('=')[0];
if (string.indexOf(attributes[0]) > -1) return string.split('-')[1];
});
keys = $.unique(keys).sort();
//console.log(JSON.stringify(keys));
var result = []
$.each(keys, function(index, key) {
var item = {};
var obj = {};
$.each(array, function(i, v) {
var k = v.split('=')[0];
//console.log("==" + k);
if (k.indexOf(key) > -1) {
//console.log("====" + k.split('-')[0]);
if ($.inArray(k.split('-')[0], attributes) > -1) {
obj[k.split('-')[0]] = v.split('=')[1];
//console.log(JSON.stringify(obj));
}
}
});
//console.log(JSON.stringify(obj));
item[key] = obj;
result.push(item);
});
$('span').text(JSON.stringify(result));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
Hope this help.

Related

Delete duplicate object(JSON) nodes - JavaScript

I have a JSON string:
var jsn = '{"header-v1":{"archives":{"is_author":"all"}},"header-v4":{"archives":{"is_author":"all"}}}';
This object is constantly updated and I want to remove duplicate values. For example, if it is:
var jsn = '{"header-v4":{"archives":{"is_author":"all"}}}';
And if the new rule set which should be added will be equal to
"header-v1":{"archives":{"is_author":"all"}}
then I want to remove "header-v4":{"archives":{"is_author":"all"}} from there, because there is a duplicate of {"archives":{"is_author":"all"}}.
Is that even possible with JavaScript?
var result = [];
$.each(subservices, function (i, e) {
var matchingItems = $.grep(result, function (item) {
return item.name === e.name && item.label === e.label;
});
if (matchingItems.length === 0){
result.push(e);
}
});
//displays result [{"name":"hello","label":"world"},{"name":"abc","label":"xyz"}]
alert(JSON.stringify(result));
JS fiddel
http://jsfiddle.net/defujjhp/
Maybe something like this you can do
var jsn = '{"header-v4":{"archives":{"is_author":"all"}}}';
var jsonObject = JSON.parse(jsn);
var newJsn = '{header-v1":{"archives":{"is_author":"all"}}}';
var newJsonObject = JSON.parse(newJsn);
var matchingKey = [];
Object.keys(newJsonObject).forEach(key => {
Object.keys(jsonObject).forEach(nkey => {
if(newJsonObject[key].toString() === jsonObject[nkey].toString()) {
matchingKey.push(nkey);
}
});
});
matchingKey.forEach(mkey => {
delete jsonObject[mkey];
});

Find duplicate values between two separate javascript objects?

I have two javascript arrays of objects:
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
and
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
I'm trying to loop through the fullDateRange array, see if any of the actualDateRange dates exist, and increment the value. But I keep getting duplicates with this code:
function outputDeltaDates(fullDateObj, responseObj) {
var dateArr = [],
valueArr = [];
$.each(fullDateObj, function(index) {
var fullDate = this;
var counter = 0
$.each(responseObj, function(index) {
var fullResponse = this;
if (fullResponse['date'] == fullDate['date']) {
valueArr.push(fullResponse['value'])
dateArr.push(fullDate['date'])
} else {
if (!dateArr.includes(fullDate['date'])) {
valueArr.push(0)
dateArr.push(fullDate['date'])
}
}
})
})
return [valueArr, dateArr]
}
To increment the objects value property if the date exists in the other array, simply loop it once and increment value if the date is found in actualDateRange
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
fullDateRange.forEach(e => {
let act = actualDateRange.find(a => a.date === e.date);
if (act) e.value += act.value;
})
console.log(fullDateRange);
To achieve expected result, push incremented counter to valueArr i.e
valueArr.push(++counter)
instead of
fullResponse['value'] (which will push actualDateRange value)
var fullDateRange=[{date:"4/1/18",value:0},{date:"4/2/18",value:0},{date:"4/3/18",value:0},{date:"4/4/18",value:0},{date:"4/5/18",value:0}]
var actualDateRange=[{date:"4/1/18",value:1},{date:"4/3/18",value:3},{date:"4/5/18",value:5}]
function outputDeltaDates(fullDateObj, responseObj) {
var dateArr = [],
valueArr = [];
$.each(fullDateObj, function(index) {
var fullDate = this;
var counter = 0
$.each(responseObj, function(index) {
var fullResponse = this;
if (fullResponse['date'] == fullDate['date']) {
valueArr.push(++counter)
dateArr.push(fullDate['date'])
} else {
if (!dateArr.includes(fullDate['date'])) {
valueArr.push(0)
dateArr.push(fullDate['date'])
}
}
})
})
return [valueArr, dateArr]
}
console.log(outputDeltaDates(fullDateRange, actualDateRange))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
code sample - https://codepen.io/nagasai/pen/rvVqdW?editors=1010

Trouble iterating through an object

I have an object that looks like this:
salesDetails:{ "1":{
"date":"06/22/2014",
"amount":"45",
"currency":"CAD",
"productID":"23",
"status":1},
"2":{
"date":"06/22/2014",
"amount":"120",
"currency":"USD",
"productID":"23",
"status":1},
"3":{
"date":"06/23/2014",
"amount":"100",
"currency":"USD",
"productID":"21",
"status":2},
"4":{
"date":"06/23/2014",
"amount":"250",
"currency":"CAD",
"productID":"25",
"status":1},
"5":{
"date":"06/23/2014",
"amount":"180",
"currency":"USD",
"productID":"24",
"status":1}
}
What i am trying to do is to get all the amount per currency of all that has status of "1" and put it in an object that should look like this:
perCurrency: {
"CAD":{
"0":"45",
"1":"250"},
"USD":{
"0":"120",
"1":"180"}
}
I was able to put all the currency in an object but I'm having trouble with the amount, the last amount from the object overlaps the previous one. I keep on getting {"CAD":{"1":"250"},"USD":{"1":"180"}} Here's my code so far.
function countPerCurrency(){
var currencyArray = new Array();
var perCurrency = {};
var totalSales = Object.size(salesDetails);
for(var i=1; i <= totalSales; i++){
var currency = salesDetails[i]["currency"];
var amount = salesDetails[i]["amount"];
var status = salesDetails[i]["status"];
var totalCurrency = Object.size(currencyAmount[currency]);
var currencyCtr = {};
if(status == 1){
if(!inArray(currency, currencyArray)){
currencyArray.push(currency);
currencyCtr[totalCurrency] = amount;
perCurrency[currency] = currencyCtr;
} else {
var currencyAdd = {};
currencyAdd[totalCurrency] = amount;
perCurrency[currency] = currencyAdd;
}
}
}
}
I know it might seem easy, but I'm lost here.. TIA! :)
The previously accepted answer uses an array of values, whereas you asked for an object. Here's an object version:
var perCurrency = {};
var currencyCount = {};
Object.keys(salesDetails).forEach(function(key) {
var obj = salesDetails[key];
var currency;
if (obj.status == 1) {
currency = obj.currency;
// If this is first for this currency, add it to objects
if (!currencyCount[currency]) {
currencyCount[currency] = 0;
perCurrency[currency] = {};
}
// Add currency values
perCurrency[currency][currencyCount[currency]++] = obj.amount;
}
});
BTW, this has nothing to do with jQuery.
Note that Object.keys is ES5 so may need a polyfill for older browsers, see MDN:Object.keys for code.
try something like this
function countPerCurrency(){
var perCurrency = {};
var totalSales = Object.size(salesDetails);
for(var i=1; i <= totalSales; i++){
var currency = salesDetails[i]["currency"];
var amount = salesDetails[i]["amount"];
var status = salesDetails[i]["status"];
if(status == '1'){
if(perCurrency.hasOwnProperty(currency)){
// if currency already present than get currency array.
var currency_arr = perCurrency[currency];
// add new value to existing currency array.
currency_arr.push(amount);
}else{
// if currency not present than create currency array and add first value;
var currency_arr = [];
currency_arr.push(amount);
// add newly created currency array to perCurrency object
perCurrency[currency] = currency_arr;
}
}
}
console.log(perCurrency);
}
output
perCurrency: {
"CAD":["45","250"],
"USD":["120","180"],
}
I have created currency array instead of key value pair
Change your code like this, i have simplified your things,
function countPerCurrency() {
var perCurrency = {};
var currencyArray = [];
for(i in salesDetails)
{
if(!perCurrency.hasOwnProperty(salesDetails[i].currency) && salesDetails[i].status === "1")
perCurrency[salesDetails[i].currency] = [];
if(salesDetails[i].status === "1")
{
currencyArray = perCurrency[salesDetails[i].currency];
currencyArray.push(salesDetails[i].amount);
perCurrency[salesDetails[i].currency] = currencyArray;
}
}
}
sorry for the late conversation anyway try like this use .each()
var CAD = new Array();
var USD = new Array();
$.each(salesDetails, function (i, value) {
if (value.status == 1) {
if (value.currency == "CAD") {
CAD.push(value.amount);
} else if (value.currency == "USD") {
USD.push(value.amount);
}
}
});
var perCurrency = {
"CAD": CAD,
"USD": USD
}
Demo

change array to json

I've been playing around with javascript and casperjs. I have the following lines of code.
casper.thenOpen('somesite', function() {
console.log('clicked ok, new location is ' + this.getCurrentUrl());
// Get info on all elements matching this CSS selector
var town_selector = 'div tr';
var town_names_info = this.getElementsInfo(town_selector); // an array of object literals
// Pull out the town name text and push into the town_names array
var town_names = [];
for (var i = 0; i < town_names_info.length; i++) {
town_names.push(town_names_info[i].text.trim());}
// Dump the town_names array to screen
utils.dump(town_names);
casper.capture('capture5.png');
});
my output is this.
[
"Address:\n \n address",
"City:\n \ncity",
"State:\n \nstate",
"Zip:\n \nzip",
]
how can I make it json? like this.
{
"Address":"address",
"City":"city",
"State":"state",
"Zip":"zip"
}
Thanks in advance.
You can use something like this:
function arrayToObject(arr) {
var out = {};
arr.forEach(function (element) {
var keyvalue = element.replace(/[\n\s]+/, '').split(':');
var key = keyvalue[0];
var value = keyvalue[1];
out[key] = value;
});
return out;
}
then you can do:
var json = JSON.stringify(arrayToObject(myArray));
Update:
> How can I change this to split only the first occurrence of colon?
Use this:
arr.forEach(function (element) {
var keyvalue = element.replace(/[\n\s]+/, '');
var key = keyvalue.substring(0, element.indexOf(':'));
var value = keyvalue.substring(key.length + 1);
out[key] = value;
});

Dynamically building array, appending values

i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;

Categories

Resources