How to access JSON-object with multiple values per key? - javascript

At the moment I am stuck with a problem that just seems stupid, but I don't know the answer to it.
I am trying to access this JSON-object:
var custom_fields =
{
"28246": 5123,5124,5125
}
I would like to get each value from that key. I would know how to access it if it was a nested-object, but it isn't sadly (it is coming from an API, which I can't change the JSON-response from sadly)
What I tried already is the following:
for (var key in custom_fields) {
if (custom_fields.hasOwnProperty(key)) {
console.log(key + " -> " + custom_fields[key]);
}
}
The problem here is that the result will be like this:
1 -> 5
2 -> 1
3 -> 2
4 -> 3
5 -> ,
6 -> 5
...etc...
Any suggestions are welcome, I am trying to access it in javascript/Jquery.
Thanks for helping in advance!

I assume that the data is in this format (note the string literals):
var custom_fields = {
"28246": "5123,5124,5125"
}
If that is the case, you can use String.split.
In your case, it would be something like this:
const values = custom_fields['28246'].split(',');
The values of they key 28246 are now stored in the new variable values as an array:
['5123','5124','5125']
If you want to parse all values to integers, I suggest using Array.map:
const valuesAsInt = custom_fields['28246'].split(',').map(value => parseInt(value);
Which will lead to this:
[5123, 5124, 5125]
Disclaimer: When using newer ECMAScript features such as Array.map, be sure to either use a browser which supports this our include a polyfill.

You can access it by using split function which will convert it into an array and then get the values from that array as below code.
var data = {
"28246": '5123,5124,5125'
}
var arr = data['28246'].split(',');
$.each(arr, function( index, value ) {
console.log(value);
});

You can split by ',' and transform each element to integer by using array.map and '+' operator:
var custom_fields =
{
"28246": "5123,5124,5125"
}
custom_fields["28246"] = custom_fields["28246"].split(',').map(el => +el);
console.log(custom_fields);
console.log(custom_fields["28246"][0], custom_fields["28246"][1], custom_fields["28246"][2]);

Related

How to properly read array from a data table on Code.Org AppLab?

I created a table called "morning" in AppLab, and one column stores data as an array (or list as it calls it). I'm able to properly add data to this array, but my problem is reading the data back (as I want to display it as a label/normal text on another page) If the numbers 1234 and 5678 are the values in the array, when I try to do
console.log(records[i].id + ': ' + records[i].buses);
The second value (buses) is the name of the column I'm trying to read back, which will result in "," rather than "1234,5678" and I'm not really sure what to do. This is the code I have so far, any help would be greatly appreciated!
readRecords("morning", {}, function(records) {
for (var i =0; i < records.length; i++) {
console.log((records[i]).id + ': ' + records[i].(buses[i]));
}
});
var ts1Buses = ["1234"];
var ts1Change;
onEvent("enterTS1", "click", function(event) {
appendItem(ts1Buses, getText("textTS1"));
updateRecord("morning", {id:1, buses:ts1Buses}, function(record, success) {
setText("textTS1", "");
});
});
The console.log statement in your longer block of code doesn't look quite right. try console.log(records[i].id + ': ' + records[i].buses); instead. if that doesn't work, please post a link to your project so that others can try to find a fix by remixing and editing it.
App Lab's data tables do not support arrays. They will have to be converted into comma-separated strings before creating or updating and converted to an array after reading.
To convert an array to a string, simply use the toString() method:
var array = ["a", "b", "c"];
console.log(array.toString()) // "a,b,c"
To convert a string into an array, use the split() method:
var string = "a,b,c";
console.log(string.split(","); // ["a", "b", "c"]

convert or parse string to JSON object

There was an interview question(Javascript) which my friend and me unable to solve it for a long time, so thought of asking here,
Question:
String:
2014<18.3,11.4,12.1,19.5,1000&&11.2,34.5,67.1,18,20000>name=sample,position=engineer,company=abc
and the end reult should be a JSON Objwct with following format. Can anyone please help to solve this issue.
Output:
{[
{"Proposal":"2014"},
{"values":"[18.3,11.4,12.1,19.5],[11.2,34.5,67.1,18]"},
{"Items":"[1000,20000]"},
{"name":"sample"},
{"position":"engineer"},
{"company":"abc"},
]}
Expecting a solution and explanation please.
Thanks,
Basky
Here is your solution.
Input string should have all the parameter, if any of the parameter is missing below code will break.
Logic is dynamic to support any number of numeric values where as last digit will consider as Items.
Logic also support the n number of key/value pair in the input string.
Check below code in console.
var JsonOutput = [];
var sRawInput = "2014<18.3,11.4,12.1,19.5,1000&&11.2,34.5,67.1,18,20000>name=sample,position=engineer,company=abc";
JsonOutput.push({ "Proposal" : sRawInput.split("<")[0] });
var oValues = sRawInput.split("<")[1].split(">")[0].split("&&");
var oActualValues = [];
var oActualItems = [];
$(oValues).each(function(Ind, Val){
oActualValues.push(Val.split(",").slice(0, Val.split(",").length - 1).join());
oActualItems.push(Val.split(",")[Val.split(",").length - 1]);
});
JsonOutput.push({ "Values" : oActualValues });
JsonOutput.push({ "Items" : oActualItems });
var OtherValues = sRawInput.split(">")[1].split(",");
$(OtherValues).each(function(Ind, Val){
JsonOutput.push(JSON.parse("{\"" + Val.split("=")[0] + "\":\"" + Val.split("=")[1] + "\"}"));
});
console.log(JsonOutput);
console.log(JSON.stringify(JsonOutput));
Note:
Values is incorrect as it should contain 2 arrays and not a single array.
Items is incorrect as it should contain numbers and not a string.
Also the outside wrapper should be an obj {}

How to replace ' / ' with '-' inside ObservableArray ? Knockout js

Well i am trying to pass an observable array via ajax call to my controller but i get every value there except date . i get something like '01-01-01' etc .
I found the issue but unable to fix that as i dont know how to replace / with - .
My ObservableArray have around 10 list items each list item holds a many properties out of those startDate holds the date like ("23/10/2014") . i just need something like ("23-10-2014") .
Tought of posting my function's and more i hope thats not required in this case i believe .
Let me explain with bit of code and sample data :
function myarray()
{
var self=this;
self.startDate=ko.observable("");
self.name=ko.observable("");
self.place=ko.observable("");
}
MyObservableArray :
self.Main= ko.observableArray();
In between i do some stuff to load Data into self.Main and i am sending self.Main to controller having data like below :
self.Main[0] holds :
startDate() -->gives you "23/10/2014" //individual observables inside onservable array
name() --> "jhon"
place()--> "croatia"
Likely
self.Main[9] holds :
startDate() --> "29/05/2012"
name() --> "pop"
place()--> "usa"
I am trying like i want to alter the self.Main() and replace the startDate and use the same self.Main to send to my controller . Once after replacing in self.Main when i check date the / should be replaced with - .
Possible solution : i can use a different observable array and push all the VM's of Main into it but i am trying to do on self.Main without using other .
If someone can show some light it is much appreciated .
What I got that you are facing problem in escaping / in replace.
Try this
"(23/10/2014)".replace(/\//g,"-") //returns "(23-10-2014)"
I tried something for you using simple JS
var arr = [{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"}];
arr.forEach(function(obj){obj.date = obj.date.replace(/\//g,"-")});
console.log(arr) //will print date field as "(23-10-2014)" for all objects.
One solution would be to add a computed value that returns the array with the right values.
self.Main = ko.observableArray([...values here...]);
self.MainComputed = ko.computed(function() {
var computedArray = [];
self.Main().forEach(function(item) {
var newItem = myarray(); //Create a new item.
newItem.name(item.name());
newItem.place(item.place());
newItem.startDate(item.startDate().replace(/\//g,"-"));
computedArray.push(newItem);
});
return computedArray;
});
Then use the computed value in the places where you need the values with -.
I can think of two other ways to solve your issue, when taken into account that you want to use self.Main:
Replace the / with - before setting startDate on your item.
Change startDate to a computed value while storing the original value in another variable.
The first solution should be pretty straight forward (provided that it is a valid solution).
The second solution would look something like this:
function myarray()
{
var self=this;
self.originalStartDate = ko.observable("");
self.name = ko.observable("");
self.place = ko.observable("");
self.startDate = ko.computed(function() {
if(self.originalStartDate()) {
//We can only replace if the value is set.
return self.originalStartDate().replace(/\//g,"-");
}
else {
//If replace was not possible, we return the value as is.
return self.originalStartDate();
}
});
}
Now when you set the values you do something like:
var item = myarray();
item.originalStartDate = "01/01/2014";
Then when you get the value of startDate you would get "01-01-2014".
I haven't used Knockout.js but you can do this with a Javascript replace:
var str = [your array value] ;
var res = str.replace("/", "-");
For more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

How to remove set of item values of array from another array in Javascript

var myFind_collections =[3,6,10,234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var pgRangeCollection = [234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
for(v=0;v<=pgRangeCollection.length;v++){
var pgMatch = pgRangeCollection[v];
clear_pg_range(pgMatch);
}
function clear_pg_range(pgMatch){
//for(d=0;d<=myFind_collections.length-1;d++){
for(d=0;d<=myFind_collections.length-1;d++){
var docFound = parseInt(myFind_collections[d]);
if(pgMatch===docFound){
myFind_collections.splice(myFind_collections[d],1);
alert(docFound + " was removed");
}
}
}
alert(myFind_collections.length);
in above code i want to remove every item in myFind_collections which equals to pgRangeCollection
i want the output as (3,6,10)
but i am getting the output as (248,249,250)
i dont know where i mistaking can anybody suggest solution for this,
Thanks in advance
Use Array.filter
var myFind_collections =[3,6,10,234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var pgRangeCollection = [234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var filtered = myFind_collections.filter(
function(a){return pgRangeCollection.indexOf(a) < 0}
); // => [ 3, 6, 10 ]
See also (filter) and also (indexOf)
The answer should be using the .filter method as already proposed by KooiInc but since IE is a requirement I would use the difference method of Lodash or Underscore:
_.difference(myFind_collections, pgRangeCollection) // [3,6,10]
Just include it via cdn:
http://cdnjs.com/libraries/lodash.js/
or if you already have jQuery:
$(myFind_collections).not(pgRangeCollection).get() // [3,6,10]

covert large array of objects into smaller array objects using javascript

I have an list of values like this from a sql database.
UserName Email ComputerName DateIssued
jjsmith jjsmith#example.com JTComputer 9/14/2013
ltjoseph ltjoseph#example.com LTComputer1 10/21/2013
KTsmith KevinTem#example.com KTComputer1 01/25/2012
ltjoseph ltjoseph#example.com LTComputer2 01/11/2013
KTsmith KevinTem#example.com KTComputer2 01/25/2012
I transform my list into an array of objects.
var user_array = [
{"username":"jjsmith", "email":"jjsmith#example.com", "computerName":"JTComputer", "dateissued":"10/21/2013"}
{"username":"ltjoseph", "email":"ltjoseph#example.com", "computerName":"LTComputer1", "dateissued":"10/21/2013"}
{"username":"KTsmith", "email":"KevinTem#example.com", "computerName":"KTComputer1", "dateissued":"01/25/2012"}
{"username":"ltjoseph", "email":"ltjoseph#example.com", "computerName":"LTComputer2", "dateissued":"01/11/2013"}
{"username":"KTsmith", "email":"KevinTem#example.com", "computerName":"KTComputer2", "dateissued":"01/25/2012"}]
A function has been created by someone else that sends emails to users, it only accepts two parameters which are strings.
So I don't want to send more than 1 email per user. So I am trying to figure out how to combine the items together so that my an example set of strings look like this.
var str1 = "ltjoseph#example.com";
var str2 = "ltjoseph, LTComputer1-10/21/2013, LTComputer2-01/11/2013";
and then fire the other user function to send emails for each of the items in the list.
function sendEmails(str1, str2);
If anyone has any ideas how i can do this. Please advise..
var by_user = {};
for (var i = 0; i < user_array.length; i++) {
if (by_user[user_array[i].username]) {
// Found user, add another computer
by_user[user_array[i].username].str2 += ', ' + user_array[i].computerName + '-' + user_array[i].dateissued;
} else {
// First entry for user, create initial object
by_user[user_array[i].username] = {
str1: user_array[i].email,
str2: user_array[i].username + ', ' + user_array[i].computerName + '-' + user_array[i].dateissued
};
}
}
Now you have the by_user object, which has a single sub-object for each user, whose str1 and str2 properties are the variables you want.
by_user['ltjoseph'].str1 => ltjoseph#example.com
by_user['ltjoseph'].str2 => ltjoseph, LTComputer1-10/21/2013, LTComputer2-01/11/2013
something like this:
var str1=array[0].email
var str2=array[0].username+", "+array[0].computerName+array[0].dateissued
or use a loop and iterate through the array
I strongly recommend bringing in a library like lodash for this sort of thing and using uniq (sample here: http://jsfiddle.net/MwYtU/):
var uniqs = lodash(user_array).pluck('email').uniq().value();
If you're doing javascript and aren't acquainted with lodash or underscore, go do that because it'll save you a lot of time. Using tried and true code is a good idea. Added bonus: if you want to see how the pros are doing something like uniq you can just look at the source code.

Categories

Resources