Related
I have String like below.
10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah
I need a way to retrieve the string by giving the ID.
E.g.: I give 20; return 150~Jude|440~Niroshan.
I think I need a HashMap to achieve this.
Key > 20
Value > 150~Jude|440~Niroshan
I am looking for an pure JavaScript approach. Any Help greatly appreciated.
If you're getting the above string in response from server, it'll be better if you can get it in the below object format in the JSON format. If you don't have control on how you're getting response you can use string and array methods to convert the string to object.
Creating an object is better choice in your case.
Split the string by # symbol
Loop over all the substrings from splitted array
In each iteration, again split the string by = symbol to get the key and value
Add key-value pair in the object
To get the value from object using key use array subscript notation e.g. myObj[name]
var str = '10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah';
var hashMap = {}; // Declare empty object
// Split by # symbol and iterate over each item from array
str.split('#').forEach(function(e) {
var arr = e.split('=');
hashMap[arr[0]] = arr[1]; // Add key value in the object
});
console.log(hashMap);
document.write(hashMap[20]); // To access the value using key
If you have access to ES6 features, you might consider using Map built-in object, which will give you helpful methods to retrieve/set/... entries (etc.) out-of-the-box.
{"profit_center" :
{"branches":
[
{"branch": {"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3310","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3311","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3312","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3313","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3314","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3315","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}}
],
"profit_center_name":"Alabama"}}
I tried accessing it in ajax through this,
data.profit_center //data here is the ajax variable e.g. function(data)
or through this data["profit_center"]
but no luck
How do I access this javascript object properly. ?
By the way that code above is from console.log(data)
EDIT:
Result from console.log(data.profit_center) and console.log(data["profit_center"]) is undefined
You can put your datain a variable like
var json = data
and you can access profit_center like
alert(json.profit_center);
alert(json.profit_center.profit_center_name); //Alabama
for(var i =0 ;i<json.profit_center.branches.length;i++){
alert(json.profit_center.branches[i]);
}
Okay I have found out why it is undefined, It is a json object so I need to parse it before i can access it like a javascript object.
var json = JSON.parse(data);
Then that's it.
First parse your data if you've not already done so.
You can access, for example, each branch_number like so:
var branches = data.profit_center.branches;
for (var i = 0, l = branches.length; i < l; i++) {
console.log(branches[i].branch.branch_number);
}
In summary, profit_center is an object and branches is an array of objects. Each element in the array contains a branch object that contains a number of keys. Loop over the branches array and for each element access the branch object inside using the key names to get the values.
The profit center name can be found by accessing the profit_center_name key on the profit_center object:
console.log(data.profit_center.profit_center_name); // Alabama
You could even use the new functional array methods to interrogate the data and pull out only those branches you need. Here I use filter to pull those objects where the purchase_order is equal to 2. Note that the numeric values in your JSON are strings, not integers.
var purchaseOrder2 = branches.filter(function (el) {
return el.branch.purchase_order === '2';
});
DEMO for the three examples
This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.
I am looking for a solution to create a single multidimensional associate array in javascript.
What I have: I have a mysql database I am accessing with php and have an array containing all fields (key,value pairs) in a single record. Their are upwards of 30 fields in each record so I am looking for a dynamic solution.
In the html coding, there is a form that is used to update a specific record in the table. I am using a function call on each input to fill a javascript array by key and value. The keys are identical to the keys in the php array.
In the function I am doing a json_encode call on the php array to pull in the "old" data to make it accessible to javascript.
What works: I am able to create a dynamic javascript associate array from the new data coming from the input function calls. I have tested this out using an alert after each call to the function.
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
This works:
var changes={};
function change(key,value) {
changes[key[value]]=value;
for (key in changes) {
alert('key: '+key+'... value: '+changes[key]);
}
}
this is along the lines of what I am looking for:
var changes={};
function change(key,value) {
var oldInfo = eval(<? echo json_encode($oldInfo); ?>); //this from the php array
changes[key[newValue]]=value;
changes[key[oldValue]]=oldInfo[key];
for (key in changes) {
alert('key: '+key+'... value: '+changes[key[newValue]]);
}
}
Can someone point me in the right direction?
To clarify:
My php array $oldInfo holds the old information from the table, for example:
{fName=>"charles",lName=>"madison", etc.}
The javascript array hold new information:
{fName=>"Charlie",lName=>"Madison", etc.}
I would like a new multidimentional array (PHP) (or object in JavaScript) that would look something like this:
{fName=>{"charles","Charlie"}, lName=>{"madison","Madison"}, etc.}
lName and fName would be the key fields that are synonymous to both the PHP array and the JavaScript object.
It's really unclear what you want, but there are a couple of serious flaws with your logic:
var changes={}; ///this one way of declaring array in javascript
No, it isn't. That's an Object, which is very different from an array.
eval(<? echo json_encode($oldInfo); ?>);
You don't need eval here. The output of json_encode is JSON, which is a subset of JavaScript that can simply be executed.
changes[key[value]]=value;
This is totally wrong, and still a single-dimensional array. Assuming key is an array, all you're doing is inverting the keys/values into a new array. If key looks like this before...
'a' => 1
'b' => 2
'c' => 3
... then changes will look like this after:
1 => 'a'
2 => 'b'
3 => 'c'
For a multidimensional array, you need two keys. You'd write something like changes[key1][key2] = value.
Your variable naming is wrong. You should never see a line that reads like this: key[value]. That's backwards. The key goes between the [], the value goes on the other side of the =. It should read something like array[key] = value.
RE: Your clarification:
This doesn't work: {fName=>{"charles","Charlie"},...}. You're confusing arrays and objects; Arrays use square brackets and implicit numeric keys (["charles", "Charlie"] for example) while Objects can be treated like associative arrays with {key1: "value1", key2: "value2"} syntax.
You want an array, where each key is the name of a property and each value is an array containing the old and new values.
I think what you want is actually quite simple, assuming the "value" you're passing into the function is the new value.
var changes = {};
var oldInfo = <?= json_encode($oldInfo) ?>;
function change(key, value) {
changes[key] = [ oldInfo[key], value ]
}
This :
changes[key[newValue]]
Should be:
changes[key][newValue]
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
Use aliases for the numeric indices to do this:
var foo = ["Joe","Blow"];
var bar = ["joe","blow"];
var names = {};
foo.fname = foo[0];
bar.fname = bar[0];
foo.lname = foo[1];
bar.lname = bar[1];
names.fname = [foo.fname,bar.fname];
names.lname = [foo.lname,bar.lname];
Given a JSON respond to a form I need to parse through the JSON elements to find error messages with their associated element the error is tied to.
The data is returned in JSON format with the error messages as the last variable pair looking like this:
"invalid":[{"field1":"Field 1 is required"}]
This ends up having an object/array for each error showing the item's name(key) along with the associated error for that field. Given that my error handling form is unaware what the key names will be how do I go about getting both the key and the value out of this object/array?
I'm using dojo on this project and I'm not familiar with it at all so I've been attempting to use dojo functions when possible if something exists that can handle this. Currently there is where I am :
var retObj = dojo.fromJson(ioargs.xhr.responseText);
dojo.forEach(retObj.invalid, function(entry,i){
console.debug(entry);
});
The console output is:
Object { field1="Field 1 is required"}
My goal is to pull out the value "field1" so I know which input field this error is assigned to, then to assign the value of field1 to that error field.
Thanks!
Dunno a single thing about Dojo, but you're looking for a pretty basic for in loop.
var retObj = dojo.fromJson(ioargs.xhr.responseText),
invalids = retObj.invalid[0],
res = {}; //here will be your final key=>value
for (var key in invalids) {
res[key] = invalids[key];
}
http://jsfiddle.net/DgXkq/
You might also be interested in https://stackoverflow.com/search?q=%5Bjavascript%5Dparsing+json
There is no way to find the key of an object if you don't have access to the parent object. I believe the best solution in this case would be to massage the JSON to pass more meaningful information to the validator, that is, an object with two properties, fieldName and errorMessage.
// Returns the name of an object's first key
function getKeyName(obj) {
for (var prop in obj) {
return prop;
}
}
// This is the response from the server
var response = { "invalid":[{"field1":"Field 1 is required"}] };
// This is going to be the massaged array that
// contains more meaningful information.
var invalids = [];
for (var i=0; i < response.invalid.length; i++) {
var obj = response.invalid[i];
var key = getKeyName(obj);
invalids.push({fieldName: key, errorMessage: obj[key]})
}
Now invalids contains an array of more meaningful error message objects like
invalids = [{fieldName: 'field1', errorMessage: 'Field 1 is required'}]
Just pass that object to your validation routine. If possible, I would change the server code to return error messages in the format I suggested so you don't have to do extra work.