Javascript, JSON - Create Table - javascript

I have a JSON Array like:
[{
"name": "abc", "month":"Jan-15","value":xyz
},{
"name": "bcd", "month":"Jan-15","value":xyz
},{
"name": "abc", "month":"Feb-15","value":xyz
},{
"name": "bcd", "month":"Feb-15","value":xyz
}]
No. of "names" may vary from month to month. But no. of "month" stays the same.
I need to create tabular overview:
Name Jan-15 Feb- 15 ...... Dec-15
abc value value ..... value
bcd value value ..... value
I'm new to Javascript and I really don't know how to get values in right columns and rows. Though I know how to dynamically add rows.
Shall I opted for "pure" solution or is better to check for a framework like e.g. AngularJS ?
Edit: I have extracted "Months" and "Names" from array and I need to do something like: value = check for this particular "name" in array and return corresponding "value".
How do I write this in JS?

It depends on the form of your data object. If you have an array object or a string object you need to use JSON.parse in order to be able to use indices and values.
If yes, then you will need to have JSON.parse(data).name to return your name values.
JSON.parse(data).month for your months and of course JSON.parse(data).value to return the xyz values.
If your data is already a JSON object then you will simply use data.name, data.month and data.value accordingly.
These links might help you get into the basics, follow the syntax and the examples.
http://www.w3schools.com/js/js_json.asp
http://www.w3schools.com/json/json_eval.asp
http://www.json.org/js.html and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Related

How to send multiple selected values, appending them as parameter to URL string - ( in JSON Server)?

I have a basic question, but still getting confused a lot.
Please note the following things before I take you to the problem
I am using JSON server as my fake API for now.
I am utilizing Material UI's select menu ( select multiple)
I am using reactJs
My Search URL is "http://localhost:3000/cars_like=Verna,Toyota,Mercedes,Audi" - this would be sent to fake api to get the filtered results in turn.
My typical Json shape -
[{id: 1, carList : ["Verna", "Toyota","Audi"]},
{id : 2, carList : ["Toyota","Audi" ]},
{id : 3, carList : ["Toyota","Mercedes" ]}, ... }];
Problem Description -
Into my MUI's select menu, I send the tags as "Toyota", "Mercedes", "Audi". I am getting "[]" an empty array as response.
I want that at least id : 3, could returned as it contains "Toyota, Mercedes", althought not "Audi".
Again there is one problem I found while filtering through multiple values into the json-server is -
When I send search params as - "Verna", "Audi", it returns me [], but it could return me an object with "id" : 1 (see above), the only difference is it contains "Toyota" between "Verna" & "Audi", and I think the (search operation breaks there and not even go to "Audi" at all).
But on the other hand, If I add filters exactly the way they are mentioned into my Json-data , say for instance "Verna", "Toyota", "Audi", they returns me the response.
How to send the parameters to the json-server, that even if the filters are not being sent into the exact order as contained in a particular json-object, it return me only those objects, whose carList array, get matched with maximum filter values.
I think I was able to describe you the problem I am facing.
All suggestions are welcome!

update nested value in javascript array

This is an odd question, but I hope someone can help me out.
I have a JS object (it's actually JSON string which is then converted back and object.).
{
"legs": [{
"pods": [{
"11": {
"id": 6,
"name": "tesla",
"text": "tesla model2",
"battery": "60"
},
"21": {
"id": 9,
"name": "porsche",
"text": "porsche electric",
"battery": "100"
}
}]
}]
}
So in my javascript I'll call a specific item... say, legs.pods[11].name
I pass that into a function like editThisField(legs.pods[11].name);
On that function editThisField(whichDataElement){.....} I'll show a modal box where the user can provide new text for the name value... what I would like is to have the whichDataElement updated to the new text such that which ever object variable I pass into that field, is updated in the legs object... I'm not sure if I'm explaining this very well, but I can't think where to start looking at a good approach to this.
Essentially I'm making a text area where I paste in the JSON, and the system allows me to edit the JSON object via modal popups. So the modal appears and dynamically shows a form based on the data in the specific sub object. When you fill in the form, the original JSON is updated... thoughts?
Not really working as I need... Maybe this helps clarify:
var mything = {
subthing: {
thisthing: "here"
}
}
var edit = mything.subthing.thisthing;
edit = "Changed";
console.log(mything); // then the listthing value should be changed.
It sounds like you're on the right track. If you pass in an object to your editThisField function you can change it's contents, but in your example you are passing in a primitive (which won't work as it's passed by value).
Another option... since you're loading a modal I assume you know what attribute you want to change so you can just specify the object keys or array indices dynamically. See example here https://jsfiddle.net/jroden1f/. Note, I changed your data model slightly as I wasn't sure why you had legs and pods as arrays and it made the example easier if I just made them objects.

How to get a sort order from wildcard property name

My JSON object looks like this and I want to sort them based on property starting with sort_
{
"sort_11832": "1",
"productsId": [
"11832",
"160",
"180"
],
"sort_160": "0",
"sort_180": "2"
}
Ideally I would like to get a result of ids based on sort order like this -
[ "160","18832","180" ]
Any suggestion on how to sort by wildcard property name. Using Javascript/Jquery ofcourse.
Here's what I'd do:
Go back to whatever is producing that truly absurd data and have them just return an array in the correct order in the first place, rather than producing an array and then repeating all the entries as separate properties with sort_ in front of them and a number.
Very, very, very, very far down in second place if the above weren't successful, I'd do this:
Call sort on the array, passing in a comparator function
In the comparator function, put "sort_" in front of each of the two values the function was given to compare, and use that property name to look up the the numeric string for that property in the object
Parse those two numeric strings into numbers
Return the result of subtracting the second one's number from the first
Code is left as an exercise to the reader.
Thanks everyone. It was a daft way of approaching this. Point taken and I have now changed the data set to something like this which makes everything very easier -
sort: [
{
\"id\": \"160\",
\"sort\": 0
},
{
\"id\": \"11832\",
\"sort\": 1
}
]

Querying/Searching for Values within JSON

For a web site I'm creating, I have to create a quote based on data provided as a JSON string from the server. I've been looking through this site (and various others) but still am unsure on the best way to query/search the data.
For example, I need to get the Area Name from the Area ID. I need to get the maximum age for an area and also the price for a given minimum/maximum age.
I also want to get an array of prices.
Is it best to create a Javascript object from the string using the eval method? Or should I be using jQuery.
Thanks for your help.
({"SkiPass":[{"Id":1,"Area":"Chamonix","Rates":[{"Id":1,"AgeMin":0,"AgeMax":2,"Price":2.5},{"Id":2,"AgeMin":3,"AgeMax":17,"Price":5.0},{"Id":3,"AgeMin":18,"AgeMax":30,"Price":6.2},{"Id":4,"AgeMin":31,"AgeMax":59,"Price":7.4}]},
{"Id":2,"Area":"Megeve","Rates":[{"Id":1,"AgeMin":0,"AgeMax":2,"Price":1},{"Id":2,"AgeMin":3,"AgeMax":17,"Price":2.0},{"Id":3,"AgeMin":18,"AgeMax":30,"Price":2.2},{"Id":4,"AgeMin":31,"AgeMax":59,"Price":4.4}]},
{"Id":3,"Area":"Verbier","Rates":[{"Id":1,"AgeMin":0,"AgeMax":2,"Price":1.5},{"Id":2,"AgeMin":3,"AgeMax":17,"Price":3.0},{"Id":3,"AgeMin":18,"AgeMax":30,"Price":4.2},{"Id":4,"AgeMin":31,"AgeMax":59,"Price":5.4}]}]})
Create a JavaScript object from the string, most definitely, but do it with legitimate JSON parsing facilities and not "eval()". You could use jQuery, but there are other solutions, such as the JSON tools available from json.org, which are small and simple.
Once it's a JavaScript object, well then your needs should guide you as to whether some query solution is necessary, or instead that it's just a simple matter of programming.
I think the best method is jLinq: http://hugoware.net/Projects/jLinq it's like doing a SQL query on JSON.
It doesn't needs jQuery.
I use it, and it's great.
Create the object from the JSON string using JSON.parse() or jQuery.parseJSON() if you are already using jQuery -- or just pass it as from the server side as JSON.
You can then iterate through the object to find the record you want. Or, you can use build your objects so that you can naturally grab data from them.
FloatLeft - as Dan points out, your task would be much easier if you could use XPath but there is no need to re-write your data in XML format. With DefiantJS (http://defiantjs.com) you can now query JSON structure with XPath expressions.
DefiantJS extends the global object JSON with the method "search", which enables XPath queries and returns an array with the matches (empty array if no matches were found). The returned array is equipped with aggregate functions as well; one of these "sortDesc".
Check out this working fiddle;
http://jsfiddle.net/hbi99/H3PR3/
var data = {
"SkiPass": [
...
{
"Id": 3,
"Area": "Verbier",
"Rates": [
{ "Id": 1, "AgeMin": 0, "AgeMax": 2, "Price": 1.5 },
{ "Id": 2, "AgeMin": 3, "AgeMax": 17, "Price": 3 },
{ "Id": 3, "AgeMin": 18, "AgeMax": 30, "Price": 4.2 },
{ "Id": 4, "AgeMin": 31, "AgeMax": 59, "Price": 5.4 }
]
}
]
},
res1 = JSON.search( data, '//SkiPass[Id=3]/Area' ),
res2 = JSON.search( data, '//*[Area and Id=3]/Rates' )
.sortDesc('AgeMax'); // <-- sorting descending by the value of "AgeMax"
document.getElementById('name').innerHTML = res1;
document.getElementById('max_age').innerHTML = res2[0].AgeMax;
document.getElementById('price').innerHTML = res2[0].Price;

Parsing the Freebase Topic HTTP API - JSON & Javascript

I am trying to parse a JSON output:
http://www.freebase.com/experimental/topic/standard?id=/en/colonel_sanders
I'd like to put the basic data into an array using Javascript. In the "properties" object I'd like to grab any "text" element one level under "properties" as a label and grab the "text" under the "values" object to match the label.
For the above I would get:
"description": "Harland David
Sanders, better known as Colonel
Sanders...
"Organizations founded": KFC
"Cause of death": Leukemia
"Date of death": Dec 16, 1980
"Place of
death": Louisville
"Date of birth":
Sep 9, 1890
"Gender": Male
etc...
I have some code which recursively runs through the JSON but I am a novice with javascript and JSON and am having a lot trouble in step one:
Firstly, grabbing the "text" trying by identifying an element as being "an element of" the main properties object; then
Secondly grabbing from the associated values array any text element (if the value is a collection then I would like to concatenate the strings from the text or otherwise ignore it).
I hope that make sense.
nb. the code I use is similar to here:
http://tlrobinson.net/projects/javascript-fun/jsondiff/
This should get you started:
<script>
function cb(response) {
var props = {};
var properties = response['/en/colonel_sanders'].result.properties;
for (var p_id in properties) {
var prop = properties[p_id];
props[prop.text]=prop.values[0].text;
}
console.log(props);
}
</script>
<script src="http://www.freebase.com/experimental/topic/standard?id=/en/colonel_sanders&callback=cb"></script>

Categories