Change the format of search result from JSON file - javascript

I am using javascript to search content from JSON file, below is my code:
var result = [];
var searchField = "equip_id";
for (var i=0 ; i < jsondata.array.length ; i++)
{
if (jsondata.array[i][searchField] == SelectedEquip) {
result.push(jsondata.array[i].group_name);
}
}
And the output is a group name with the following format:
["groupname"]
I only want the groupname without [] and "". Because I need to use the groupname to search another JSON file.
Anyone can help solve this problem?

If you want the result as a string, how about:
// Sample Data
var jsondata = {
array: [{
equip_id: 1,
group_name: "a"
}, {
equip_id: 2,
group_name: "b"
}, {
equip_id: 3,
group_name: "c"
}]
}, SelectedEquip = 3;
// Actual code
var result = '';
var searchField = "equip_id";
for (var i = 0; i < jsondata.array.length; i++) {
if (jsondata.array[i][searchField] == SelectedEquip) {
result = jsondata.array[i].group_name;
}
}
// Sample output
console.log(result);
Using your code above, result[0] will give you the same output. There's just no need to create and push to an array, if you are dealing with a single value.

Related

Creating a nested JSON object with Google Sheets

I am trying to teach myself some AppScript/Javascript. As an exercise, I am want to generate the following JSON object
[
{
"config_type": "City Details",
"config_data": [
{
"city_type": "MAJOR_CITY",
"city_data": [
{
"city_name": "BIGFOOLA",
"monetary_data": [
{
"currency_data": [
{
"dollars": 1000
}
]
}
]
}
]
}
]
}
]
I want to be able to enter only few details like "City Details", "MAJOR_CITY", and the dollar value - 1000 in a Google Sheet. The script should be able to generate the above JSON.
So I started by creating the names of all the Arrays and Objects in one row. In front of the the arrays, there was a blank cell and in front of the object the value. The Sheet looks like this
A B
config_type City Details
config_data
city_type MAJOR_CITY
city_data
city_name BIGFOOLA
monetary_data
currency_data
dollars 1000
I am able to get all of the details in a single object, but struggling to nest them under each other. How do I go about this?
Edit :Here is what I have for now
function doGet(){
var result={}
var rewardSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CITY")
var reward_data = rewardSheet.getRange("A1:B13").getValues();
result = getJsonArrayFromData(reward_data);
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON)
}
function getJsonArrayFromData(data)
{
var column_headers = data[0];
var col_len = column_headers.length;
var row = [];
var reward_obj = [];
var config_obj = {};
var config_type = {};
var config_data = [];
var reward_type = {};
var reward_data = [];
var reward_name = {};
var reward_data_2 = [];
var currency_data = [];
var curreny_obj = {};
var rewardSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CITY")
var row_items = rewardSheet.getRange(1,1,data.length,1).getValues();
//Logger.log(row_items);
for(var i=0;i<data.length;i++){
row = data [i];
config_type ={};
reward_type[config_type]={};
reward_name[reward_type]={};
//Logger.log(row);
for(var r=0;r<row.length;r++)
{
config_type[row[r]] = row[r+1];
reward_type[row[r]] = row[r+1];
reward_name[row[r]] = row[r+1];
}
config_data.push(config_type,reward_type,reward_name);
//reward_data.push(reward_name);
reward_obj = config_data;
}
Logger.log(reward_obj);
return reward_obj;
}
Ps: I know the JSON is messy, but its just to understand and teach myself.
You hard-coded a bunch of property names as variables; this is not a good approach.
Here is how one can do this. The variable output holds the object we'll return at the end, while currentObject points to the object that is due to be filled next. When it comes to filling it, we either have a scalar value data[i][1] to put in, or we don't, in which case a new object is created and becomes the new currentObject.
function formJSON() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("CITY");
var data = sheet.getDataRange().getValues();
var currentObject = {};
var output = [currentObject]; // or just currentObject
for (var i = 0; i < data.length; i++) {
if (data[i][1]) {
currentObject[data[i][0]] = data[i][1];
}
else {
var newObject = {};
currentObject[data[i][0]] = [newObject]; // or just newObject
currentObject = newObject;
}
}
Logger.log(JSON.stringify(output));
}
The output is
[{"config_type":"City Details","config_data":[{"city_type":"MAJOR_CITY","city_data":[{"city_name":"BIGFOOLA","monetary_data":[{"currency_data":[{"dollars":1000}]}]}]}]}]
or, in beautified form,
[{
"config_type": "City Details",
"config_data": [{
"city_type": "MAJOR_CITY",
"city_data": [{
"city_name": "BIGFOOLA",
"monetary_data": [{
"currency_data": [{
"dollars": 1000
}]
}]
}]
}]
}]
Incidentally, I don't see why you wanted to put every object in an array. A property can be another object. Removing square brackets on the commented lines we would get
{
"config_type": "City Details",
"config_data": {
"city_type": "MAJOR_CITY",
"city_data": {
"city_name": "BIGFOOLA",
"monetary_data": {
"currency_data": {
"dollars": 1000
}
}
}
}
}

How to convert JSON data to Array in JQuery?

I am getting Json data from result as following,
var chartData1 = [
{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},
{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},
{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}
]
I want to convert it to following,
var chartData2 = [
['Action', 'value', 'platform'],
['Twitter', '1.00', 2],
['WhatsApp', '1.00', 3],
['Messaging', 'WhatsApp', 4],
]
I have used different methods like parseJSON,map,etc , but i could not get expected results.
Can you help me out from this.
I'm assuming you first need to parse valid JSON string containing your data and then convert each row with object to array. And prepend whole array with array with column names. Following code will exactly do that:
var chartDataString = "[{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}]";
var chartData = JSON.parse(chartDataString);
var keys = [];
var data = [];
var row;
for (var i = 0; i < chartData.length; i++) {
row = [];
for (var key in chartData[i]) {
if (i === 0) {
keys.push(key);
}
row.push(chartData[i][key]);
}
if (i === 0) {
data.push(keys);
}
data.push(row);
}
console.log(data);
The following will convert it to an array, providing that it is already parsed as an object.
var chartData2 = Object.keys(chartData1).map(function(k) { return chartData1[k] });
console.log(chartData2);
Probably the most ideal here is to map original array to new structure:
var chartData1 = [
{"Action":"Twitter","value":"1.00","platform":"2"},
{"Action":"WhatsApp","value":"1.00","platform":"3"},
{"Action":"Messaging","value":"1.00","platform":"4"}
];
var result = chartData1.map(function(el) {
return [el.Action, el.value, el.platform];
});
result.unshift(['Action', 'value', 'platform']);
alert(JSON.stringify(result, null, 4));

selecting particular keys from json data

I have a array as:
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic
Json data comming from backend as:
info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84}
suppose I want to select market cap then I can do info.marketCap. But I want to select only those json values which keys are equals to cols i.e. info.ticker, info.highPrice, info.lowPrice
and assign N/A to those which is undefined in json but present in cols array i.e info.lastPrice = "N/A"
Note: cols changes from time to time
Here is what I have got so far
SyScreener.fillScreenerResult = function(info) {
var cols = ["ticker", "highPrice", "lowPrice", "openPrice", "lastPrice", "currentVol", "avgVol"];
var data = [];
for(var i=0; i<info.length; i++) {
var jsonKeys = Object.keys(info[i]);
for(var j=0; j<jsonKeys.length; i++) {
if(cols.contains(jsonKey[j])) {
// TODO something like - data.push([info[i].jsonKey[j])
} else {
// TODO something like - info[i].colsValue = "N/A"
}
}
}
SyUtils.createDataTable("screener_result", data);
};
do you mean something like this:
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"];
info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84};
for(var c = 0, clen = cols.length; c < clen; c++) {
if( !(cols[c] in info) ) {
console.log("N/A");
}
else {
console.log(info[cols[c]]);
}
}
Demo:: jsFiddle
I may not be reading your question correctly but from my understanding I might suggest something like this.
for (var i=0; i<cols.length; i++) {
var fieldName = cols[i];
if (!info.hasOwnProperty(fieldName)) {
info[fieldName] = 'N/A';
}
}
This simply iterates through each field name in cols and checks if it is a property of the info JSON object. If it isn't already present the loop adds the property with a value of 'N/A'.
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"]
var info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84}
var output = {};
for(each in info) {
var index = cols.indexOf(each)
if(index != -1) {
output[each] = info[each];
//remove extra already checked element
cols.splice(index,1)
}
}
//append remaining keys
for(var i=0;i<cols.length;i++) {
output[cols[i]] = "N/A"
}
console.log(output)
//output Object {ticker: "AAPL", lowPrice: 42.72, highPrice: 42.84, lastPrice: "N/A"}
First thing, you nedd deserialize you JSON data.
To do this using jQuery use the function parseJson that you can find here
http://api.jquery.com/jquery.parsejson/
once you deserialized it, you can do whatever you want with this data since you manipulate it as a plain javascript array. Hope this helps.

javascript increment name of variable

I get an object with partial results of match from database.
[Object { home1=4, away1=3, home2=4, away2=5, home3=6, away3=7, home4=6, away4=5, home5=3, away5=6}]
home1 it's a result of first part of home team,
away1 -> away team, home2 it's a result of second part of home team... etc etc
data in my case is each row, which i get from database.
In rows i have td with class: home1, home2, home3, away1, away2 and there are values of corresponding part of match.
I want to check if value is equal to what I got from database.
Something like this
if ($('.home1') === data[index].home1;
if($('.away2') === data[index].away2;
there should be some loop. I have no idea how to do this, I thought about an array
var array = [
{
home1: data[index].home1,
away1: data[index].away1
},
{
home2: data[index].home2,
away2: data[index].away2
},
{
home3: data[index].home3,
away3: data[index].away3
},
{
home4: data[index].home4,
away4: data[index].away4
},
{
home5: data[index].home5,
away5: data[index].away5
}
]
and then for loop:
for(var X=0; X<5;X++){
homeX == data[index].homeX
}
How can I increment name of variable by eval function? or is there any other solution? I'm very confused.
You can access object properties using operator []:
for(var i=0; i<array.length; i++)
{
var item = array[i];
var homePropertyName = 'home' + (i+1);
//now you can access homeX property of item using item[homePropertyName]
//e.g. item[homePropertyName] = data[index][homePropertyName]
}
Maybe you should use a little different structure which might fit your needs better, like this:
array = [
0: array [
"home": "Text for home",
"away": "Text for away"
],
1: array [
"home": "",
"away": ""
]
// More sub-arrays here
];
You can also initialize it with a for loop:
var array = new Array();
var i;
for (i = 0; i < 4; i++) {
array[i] = [
"home": "",
"away": ""
];
}
Or like this:
array[0]["home"] = "Text for home";
array[0]["away"] = "Text for away";
You can use this structure for the data-array also, and then use a for-loop to go through them both (like if you wish to find an element):
var result = NULL;
for (i = 0; i < array.length; i++) {
if ( (array[i]["home"] == data[index]["home"]) &&
(array[i]["away"] == data[index]["away"])
) {
// Found matching home and away
result = array[i];
break;
}
}
if (result != NULL) {
alert("Found match: " + result["home"] + " - " + result["away"]);
}
else {
alert("No match");
}
PS: Code is not tested, let me know if something is wrong.
you can access global properties in browser via window object like this (fiddle):
value1 = "ONE";
alert( window['value'+1] );
But it is not good design. You should look into how to properly format JSON object.
I have something like this:
for(var i=0; i<2; i++)
{
var item = ARR[i];
for(var x=0;x<5;x++){
var hPropertyName = 'home_p' + (x+1);
var aPropertyName = 'away_p' + (x+1);
item[hPropertyName] = ARR[i][hPropertyName];
item[aPropertyName] = ARR[i][aPropertyName];
}
and it works when i create an array:
var ARR = [
{
home_p1: 4,
away_p1: 5,
home_p2: 8,
away_p2: 9,
home_p3: 2,
away_p3: 1,
home_p4: 5,
away_p4: 3,
home_p5: 3,
away_p5: 2
},
{
home_p1: 6,
away_p1: 1,
home_p2: 1,
away_p2: 2,
home_p3: 3,
away_p3: 4,
home_p4: 5,
away_p4: 6,
home_p5: 3,
away_p5: 2
}
];
but I don't have to create an array, because i have to work on object which I get from database :
[Object { event_id=19328, home_result=3, away_result=2, home_p1=4, away_p1=3, home_p2=1, away_p2=2 ...... }]
I'm only interested in these parameters --> home_p , away_p
I want to push it to my array to looks like ARR. I think i should convert an object which I get to an array
If you are using string name for your attributes then you could try using template literals?
var someObject = {}
for(let i=0 ; i<values.length ; i++){
someObject[`home${i+1}`] = values[i];
}
and if you need it to be ES5 you could just use string concatenation. Below is a working example:
values = [1,2,3,4,5];
let someObject = {};
for(let i=0 ; i<values.length ; i++){
someObject[`value${i+1}`]=values[i];
}
console.log(someObject.value1);
console.log(someObject.value2);
console.log(someObject.value3);
console.log(someObject.value4);
console.log(someObject.value5);

Setting up a variable length two-dimensional array

I have a string as follows :
Panther^Pink,Green,Yellow|Dog^Hot,Top
This string means I have 2 main blocks(separated by a '|') :
"Panther" and "Dog"
Under these two main blocks, I have, lets say "subcategories".
I wanted to create a 2-dimensional array represented (in logic) as follows :
Panther(Array 1) => Pink(Element 1),Green(Element 2), Yellow(Element 3)
Dog(Array 2) => Hot(Element 1), Top(Element 2)
Also,I want to be able to add a main block, lets say "Cat" with possible categories "Cute,Proud" to the two dimensional array
I've managed to get an Array containing "Panther^Pink,Green,Yellow" and "Dog^Hot,Top" by using JavaScript's split function.
Note that this string is received via Ajax and can be of any length, though the format shown above is always used.
----------------------------- EDIT ----------------------------
Ok, my script so far is :
$(document).ready(function(){
appFunc.setNoOfAppBlock('Panther^Pink,Green,Yellow|Dog^Hot,Top');
appFunc.alertPing();
});
var appFunc = (function(stringWithSeper) {
var result = {},
i,
categories = new Array(),
subcategories;
return {
setNoOfAppBlock: function(stringWithSeper){
categories = stringWithSeper.split("|");
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
},
alertPing: function(){
alert(result["Panther"][1]);
}
};
})();
However, the function "alertPing" isn't "alerting" anything.What am am I doing wrong ?
To me the most logical representation of your data:
Panther^Pink,Green,Yellow|Dog^Hot,Top
Is with a JavaScript object with a property for each category, each of which is an array with the subcategories:
var data = {
Panther : ["Pink", "Green", "Yellow"],
Dog : ["Hot", "Top"]
}
You would then access that by saying, e.g., data["Dog"][1] (gives "Top").
If that format is acceptable to you then you could parse it as follows:
function parseData(data) {
var result = {},
i,
categories = data.split("|"),
subcategories;
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
return result;
}
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var data = parseData(str);
Assuming you're trying to parse your data into something like this:
var result = {
Panther: ["Pink", "Green", "Yellow"],
Dog: ["Hot", "Top"]
}
you can use string.split() to break up your string into subarrays:
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var result = {}, temp;
var blocks = str.split("|");
for (var i = 0; i < blocks.length; i++) {
temp = blocks[i].split("^");
result[temp[0]] = temp[1].split(",");
}
Data can then be added to that data structure like this:
result["Cat"] = ["Cute", "Proud"];
Data can be read from that data structure like this:
var dogItems = result["Dog"]; // gives you an array ["Hot", "Top"]
You can use something like:
function parseInput(_input) {
var output = [];
var parts = _input.split('|');
var part;
for(var i=0; i<parts.length; i++) {
part = parts[i].split('^');
output[part[0]] = part[1].split(',');
}
return output;
}
Calling parseInput('Panther^Pink,Green,Yellow|Dog^Hot,Top'); will return:
output [
"Panther" => [ "Pink", "Green", "Yellow" ],
"Dog" => [ "Hot", "Top" ]
]
To add another item to the list, you can use:
output["Cat"] = ["Cute", "Proud"];

Categories

Resources