change array to json - javascript

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;
});

Related

Replace last letters in array of strings Javascript

I need to do as follows:
I've got an array of strings containing last names. Some of them ends with letter 'i'.
manLastNames = ["testowski","bucz","idzikowski","gosz"];
I need to make a function which will iterate over this array of strings and if there is an element ending with 'i', I need to replace this 'i' for 'a', otherwise just leave string as it is.
At the end I want to have another array where all last 'i's are replaced with 'a's.
womanLastNames = ["testowska","bucz","idzikowska","gosz"];
This is what I have now, but Im pretty sure that it start being crap at some point
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = new Array(4);
for (var i=0; i<manLastNames.length; i++) {
var lastName = manLastNames[i];
if (lastName.substr(lastName.length - 1, 1) == 'i') {
lastName = lastName.substr(0, lastName.length - 1) + 'a';
}
}
for (var i=0; i<womanLastNames.length; i++) {
womanLastNames[i] = lastName[i];
}
console.log(womanLastNames);
}
rep();
Try the code:
var manNames = ["testowski","bucz","idzkowski","gosz"];
var womanNames = manNames.map(function(name) {
return name.endsWith("i") ? name.slice(0, -1) + "a" : name;
});
console.log(womanNames)
If your interpreter supports ES6, the following is equivalent:
names.map((name)=>name.endsWith("i") ? name.slice(0, -1) + "a" : name)
Here is solution
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames =[];
for (var i=0; i<manLastNames.length; i++) {
var lastName = manLastNames[i];
if (lastName.charAt(lastName.length - 1) == 'i') {
lastName = lastName.substr(0, lastName.length - 1) + 'a';
}
womanLastNames.push(lastName);
}
console.log(womanLastNames);
}
rep();
Another solution is to use .map method like this, using a callback function:
var manLastNames = ["testowski","bucz","idzikowski","gosz"];
function mapNames(item){
return item[item.length-1]=='i' ? item.substr(0, item.length-1) + "a" : item;
}
console.log(manLastNames.map(mapNames));
Depending on how efficient you need to be, you can use regular expressions to do both tasks:
var new_name = name.replace(/i$/, 'a');
will replace the last "i" in a string with "a" if it exists
var new_name = name.replace(/i/g, 'a');
will replace all "i"s in a string with "a".
var names = ["testowski", "bucz", "idzkowski", "gosz"];
console.log("original", names);
var last_i_replaced = names.map(function(name) {
return name.replace(/i$/, 'a');
});
console.log("last 'i' replaced", last_i_replaced);
var all_i_replaced = names.map(function(name) {
return name.replace(/i/g, 'a');
});
console.log("all 'i's replaced", all_i_replaced);
This should work:
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = manLastNames;
for(var i=0; i<manLastNames.length;i++){
if(manLastNames[i].charAt(manLastNames[i].length-1)=='i'){
womanLastNames[i]=manLastNames[i].substr(0,womanLastNames[i].length-1)+'a';
}
}
console.log(womanLastNames);
}
rep();
Here is another solution
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = []
manLastNames.forEach(x => {
if (x.charAt(x.length-1) === "i") womanLastNames.push(x.slice(0,-1).concat("a"));
else womanLastNames.push(x);
});
console.log(womanLastNames);

create an object array from a form in 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.

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

Build object in JavaScript from PHP form input name

There are a couple of similar questions but none covers the case when a string looks like some-name[][some-key]. I have tried JSON.parse('some-name[][some-key]'); but it doesn't parse it.
Is there a way to convert such string to a JavaScript object that will look like { 'some-name': { 0: { 'some-key': '' } } }?
This is a name of a form field. It's normally parsed by PHP but I'd like to parse it with JavaScript the same way. I basically have <input name="some-name[][some-key]"> and I'd like to convert that to var something = { 'some-name': { 0: { 'some-key': VALUE-OF-THIS-FIELD } } }.
Try this:
JSON.parse('{ "some-name": [ { "some-key": "" } ] }');
I don't know exactly how you're doing this, but assuming they are all that format (name[][key]) and you need to do them one by one - this works for me:
var fieldObj = {};
function parseFieldName(nameStr)
{
var parts = nameStr.match(/[^[\]]+/g);
var name = parts[0];
var key = typeof parts[parts.length-1] != 'undefined' ? parts[parts.length-1] : false;
if(key===false) return false;
else
{
if(!fieldObj.hasOwnProperty(name)) fieldObj[name] = [];
var o = {};
o[key] = 'val';
fieldObj[name].push(o);
}
}
parseFieldName('some-name[][some-key]');
parseFieldName('some-name[][some-key2]');
parseFieldName('some-name2[][some-key]');
console.log(fieldObj); //Firebug shows: Object { some-name=[2], some-name2=[1]} -- stringified: {"some-name":[{"some-key":"val"},{"some-key2":"val"}],"some-name2":[{"some-key":"val"}]}
o[key] = 'val'; could of course be changed to o[key] = $("[name="+nameStr+"]").val() or however you want to deal with it.
Try this:
var input = …,
something = {};
var names = input.name.match(/^[^[\]]*|[^[\]]*(?=\])/g);
for (var o=something, i=0; i<names.length-1; i++) {
if (names[i])
o = o[names[i]] || (o[names[i]] = names[i+1] ? {} : []);
else
o.push(o = names[i+1] ? {} : []);
}
if (names[i])
o[names[i]] = input.value;
else
o.push(input.value);
Edit: according to your updated example, you can make something like this (view below). This will work - but only with the current example.
var convertor = function(element) {
var elementName = element.getAttribute('name');
var inpIndex = elementName.substring(0, elementName.indexOf('[')),
keyIndex = elementName.substring(elementName.lastIndexOf('[') + 1, elementName.lastIndexOf(']'));
var strToObj = "var x = {'" + inpIndex + "': [{'" + keyIndex + "': '" + element.value + "'}]}";
eval(strToObj);
return x;
};
var myObject = convertor(document.getElementById('yourInputID'));
Example here: http://paulrad.com/stackoverflow/string-to-array-object.html
(result is visible in the console.log)
old response
Use eval.. but your string must have a valid javascript syntax
So:
var str = "arr[][123] = 'toto'";
eval(str);
console.log(arr);
Will return a syntax error
Valid syntax will be:
var str = "var arr = []; arr[123] = 'toto'";
var x = eval(str);
console.log(arr);

javascript array - accessing json type of objects

The code:
function getDummyDetails(){
var userDetailsMap = [];
userDetailsMap.push({key:'APPCODE', value:'41'});
userDetailsMap.push({key:'WORKERNUMBER', value:'1234567'});
userDetailsMap.push({key:'ACCOUNTID', value:'DEVELOP'});
userDetailsMap.push({key:'NAMEFIRST', value:'John'});
userDetailsMap.push({key:'NAMELAST', value:'Developer'});
return userDetailsMap;
}
function someOtherFunction () {
var userDetails = getDummyDetails();
document.getElementById("userName").innerHTML = "User Name: " + userDetails[3].value + ", " + userDetails[4].value;
}
Here, it works fine but I can not use the array index here like userDetails[3].value. I was trying to do something like this
userDetails["APPCODE"].value; // just a pseudo code
How can I index this array with that string values but not an integer?
You should create an object instead of an array. That way you'll be able to access it via its key:
function getDummyDetails() {
return {
'APPCODE':'41',
'WORKERNUMBER':'1234567',
'ACCOUNTID':'DEVELOP',
'NAMEFIRST':'John',
'NAMELAST':'Developer'
};
}
function someOtherFunction () {
var userDetails = getDummyDetails();
userDetails["APPCODE"] // 41 - use it however you want...
}
You need to create an object, not an array:
var userDetailsMap = {
APPCODE:41
}
var value = userDetailsMap["APPCODE"];//value now = 41
If you don't want to change your structure, you can iterate over your array:
for (var i = 0, len = userDetailsMap.length; i < len; i++) {
if (userDetailsMap[i].key == 'APPCODE') {
var val = userDetailsMap[i].value;
// do something with the value here
}
}

Categories

Resources