Printing Information from JSON string - javascript

I have the following JSON string:
var txt=
{
"people":
[{
"person":
{
"firstname":"Jane",
"lastname":"Doe"
}
},
{
"person":
{
"firstname":"John",
"lastname":"Smith"
}
}
]
};
I want the program to alert that there are two people in the list, but when I do my count function, it only says 1 (gets to 'people' then doesn't go deeper into the list).
Here is the fiddle:
http://jsfiddle.net/LipeeVora/rsBYb/3/

You don't need a to write a counting loop. txt.people.length will give you the count, as txt.people is an array object.
See my revised fiddle for an example: http://jsfiddle.net/rsBYb/5/
Your loop was counting the elements in txt - of which there is only one (the people array). It would work fine if you instead use txt.people in the loop. You really want to count the elements in txt.people, not txt.
Example of this: http://jsfiddle.net/rsBYb/8/

txt.people.length
will give you the correct answer
http://jsfiddle.net/rsBYb/6/

It is because you count people and not persons.
Change your loop to this:
for ( property in txt.person )
{
count++;
}
alert("count = " + count);

This should work:
txt.people.length
You might have to do a JSON.parse depending on where you're pulling your JSON string from (if you're doing anything with it outside of the fiddle)

Related

Function returning object instead of Array, unable to .Map

I'm parsing an order feed to identify duplicate items bought and group them with a quantity for upload. However, when I try to map the resulting array, it's showing [object Object], which makes me think something's converting the return into an object rather than an array.
The function is as follows:
function compressedOrder (original) {
var compressed = [];
// make a copy of the input array
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 1;
var a = new Object();
// loop over every element in the copy and see if it's the same
for (var w = i+1; w < original.length; w++) {
if (original[w] && original[i]) {
if (original[i].sku == original[w].sku) {
// increase amount of times duplicate is found
myCount++;
delete original[w];
}
}
}
if (original[i]) {
a.sku = original[i].sku;
a.price = original[i].price;
a.qtty = myCount;
compressed.push(a);
}
}
return compressed;
}
And the JS code calling that function is:
contents: compressedOrder(item.lineItems).map(indiv => ({
"id": indiv.sku,
"price": indiv.price,
"quantity": indiv.qtty
}))
The result is:
contents: [ [Object], [Object], [Object], [Object] ]
When I JSON.stringify() the output, I can see that it's pulling the correct info from the function, but I can't figure out how to get the calling function to pull it as an array that can then be mapped rather than as an object.
The correct output, which sits within a much larger feed that gets uploaded, should look like this:
contents:
[{"id":"sku1","price":17.50,"quantity":2},{"id":"sku2","price":27.30,"quantity":3}]
{It's probably something dead simple and obvious, but I've been breaking my head over this (much larger) programme till 4am this morning, so my head's probably not in the right place}
Turns out the code was correct all along, but I was running into a limitation of the console itself. I was able to verify this by simply working with the hard-coded values, and then querying the nested array separately.
Thanks anyway for your help and input everyone.
contents: compressedOrder(item.lineItems).map(indiv => ({
"id": indiv.sku,
"price": indiv.price,
"quantity": indiv.qtty
}))
In the code above the compressedOrder fucntion returns an array of objects where each object has sku, price and qtty attribute.
Further you are using a map on this array and returning an object again which has attributes id, price and quantity.
What do you expect from this.
Not sure what exactly solution you need but I've read your question and the comments, It looks like you need array of arrays as response.
So If I've understood your requirement correctly and you could use lodash then following piece of code might help you:
const _ = require('lodash');
const resp = [{key1:"value1"}, {key2:"value2"}].map(t => _.pairs(t));
console.log(resp);
P.S. It is assumed that compressedOrder response looks like array of objects.

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"]

How to get only 1st element of JSON data?

I want to fetch only 1st element of json array
my json data :
{
id:"1",
price:"130000.0",
user:55,
}
{
id:"2",
price:"140000.0",
user:55,
}
i want to access the price of 1st json element
price : "13000.0"
my code
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
});
but my output
is '1'
Assuming that you have array of objects
var arr = [{
id:"1",
price:"130000.0",
user:55,
},
{
id:"2",
price:"140000.0",
user:55,
}]
console.log(arr[0].price)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You data isn't valid JSON, JSON data key must be wrap within double quote, but your data isn't wrapped in double quote
var data = [{
"id":"1",
"price":"130000.0",
"user":55
},{
"id":"2",
"price":"140000.0",
"user":55
}]
console.log(data[0]["price"]);
Hello You just need to add [] from starting and ending point of your json string. see here var data = JSON.parse( '[{ "id":"1","price":"130000.0","user":55},{"id":"2","price":"140000.0","user":55}]');
var priceValue = 0;
$.each(data, function(index, element) {if(index == 0){ priceValue = element.price;}});console.log(priceValue);
Your answer will be 13000.0
The element having the your JSON data means, we can able to use below code to get the first JSON data.
element[0].price
Thanks,
You are using for each loop and in function you get 2 params first one is index and second is the element itself. So this will iterate through all elements.
$.each(data_obj, function(index, element) {
$('#price').append(element.price);
});
If you just want to get first element
$('#price').append(data_obj[0].price);
var my_first_json_obj = data_obj[0]; // Your first JSON obj (if it's an array of json object)
var my_price = my_first_json_obj.price; // Your price
$('#price').append(my_price);
If you want only the first item's price, you don't need a loop here.
$('#price').append(data_obj[0].price);
would work here.
For further reading you can refer here
Following is the solution worked for my problem
I use return false;
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
return false;
});
Which gives only 1st value of array elements.

How can I do more elegantly several _.has checks?

I have an object like this
myObject:{"property1": "valueX",
"property2": "valueY",
"property3": "valueZ",
"property4": "valueV",
"property5": "valueW"}
and I want to make sure that none of my object properties names match several strings.
The most intuitive way I found is this one:
if( !_.has(myObject, "TestingValue1")&&
!_.has(myObject, "TestingValue2")&&
!_.has(myObject, "TestingValue3")&&
!_.has(myObject, "TestingValue4")){
//do something
}
But if I have too much property names to check, it is becoming quite a large piece of code.
I am trying to come up with a more elegant solution. I feel it is almost ok but I does not appear to work (it always returns true). Here it is:
var TestingValues = ["TestingValue1", "TestingValue2", "TestingValue3"]
if (!_.every(TestingValues, _.partial(_.has, myObject))){
//do something
}
Can you tell me what is wrong? How should I declare TestingValues?
EDIT:
#Sergiu Paraschiv I used different values in myObject and the test array only for making it easier to read. Of course I tested it with identical values.
You are right, I just realized it works. I didn't at first because it does not work as intended. I mixed things up: I want to return false if any of the item in the string array matches any of the attributes of myObject
You can do :
var TestingValues = [ "TestingValue1", "TestingValue2", "TestingValue3" ];
if(!_.isEmpty(_(myObject).pick(TestingValues)){...
or as you suggested yourself :
if (!_.some(TestingValues, _.partial(_.has, myObject)))
Alternative:
_some(TestValues, function(test) { return _.indexOf(_.values(myObject), test) != -1});
You can try
var testingValues = ["TestingValue1", "TestingValue2", "TestingValue3"];
var myObj = {
"property1": "valueX",
"property2": "valueY",
"property3": "valueZ",
"property4": "valueV",
"property5": "valuez"
};
var result = _.every(myObj, function(value, key, obj){
return !_.contains(testingValues, value);
});
console.log(result);

Dynamic Associative Array Creation in Javascript from JSON

It sounds a lot more complicated than it really is.
So in Perl, you can do something like this:
foreach my $var (#vars) {
$hash_table{$var->{'id'}} = $var->{'data'};
}
I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery.
I've tried the following:
hash_table = new Array();
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
Where data is a JSON object gotten from a $.getJSON call. It looks more or less like this (my JSON syntax may be a little off, sorry):
{
results:{
datasets_a:{
dataset_one:{
data:{
//stuff
}
extra_info:{
//stuff
}
}
dataset_two:{
...
}
...
}
datasets_b:{
...
}
}
}
But every time I do this, firebug throws the following error:
"XML filter is applied to non-xml data"
I think you can use the JSON response as an associative array. So you should be able to go directly in and use the JSON.
Assuming you received the above example:
$('result').innerHTML = data['results']['dataset_a']['dataset_two']['data'];
// Or the shorter form:
$('result').innerHTML = data.results.dataset_a.dataset_two.data;
Understand that I haven't tested this, but it's safer to use the square brackets with a variable than it is to use parenthesis plus the name with the dot accessor.
Your example is failing because of some convoluted logic I just caught.
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
Now, the foreach loop goes through the variable data.results to find the internal elements at a depth of 1. The item it finds is given to the lambda with the key of the item. AKA, the first result will be name = "datasets_a" item = object. Following me so far? Now you access the returned hash, the object in item, as though it has the child key in name ... "datasets_a". But wait, this is the object!
If all else fails... write your result JSON into a text field dynamically and ensure it is formatted properly.
Why would you want to change an array into another array ?-)
-- why not simply access the data, if you want to simplify or filter, you can traverse the arrays of the object directly !-)
This works. Just dump it into a script block to test.
d = {
'results':{
'datasets_a':{
'dataset_one':{
'data':{
'sample':'hello'
},
'extra_info':{
//stuff
}
},
'dataset_two':{
///
}
///
},
'datasets_b':{
///
}
}
}
alert(d.results.datasets_a.dataset_one.data.sample)
I hope this pasted in correctly. This editor doesn't like my line breaks in code.
d = {
'results':{
'datasets_a':{
'dataset_one':{
'data':{
'sample':'hello'
},
'extra_info':{
//stuff
}
},
'dataset_two':{
///
}
///
},
'datasets_b':{
///
}
}
};
alert(d.results.datasets_a.dataset_one.data.sample)

Categories

Resources