Append JSON elements in Ember - javascript

I am having an array with some of values (i.e., [1,2,3,4,5]), now i have to convert this array elements into JSON format.
I tries this one,
var Jsondata = {};
for (i = 0; i < Response.get('firstname').length; i++) {
Jsondata.push({
name : Response.get('firstname')[i]
});
}
Ember.Logger.debug(Jsondata );
but it shows some error :
carousel.js:575 Uncaught TypeError: Jsondata.push is not a function(…)
how to append json elements in ember?

Can you please try like this.
var Jsondata = [];
for (i = 0; i < Response.get('firstname').length; i++) {
Jsonvalue = {
name : Response.get('firstname')[i]
}
Jsondata.push(Jsonvalue);
}

Your Jsondata is a hash instead of an array. If you change it to an array your code should work. Your issue is unrelated to Ember

Related

Get JSON stringify value

I have JSON stringify data like this :
[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]
I want to get only price value of that data. I have tried this way but it doesn't work.
var stringify = JSON.stringify(values);
for(var i = 0; i < stringify.length; i++)
{
alert(stringify[i]['price']);
}
How could I to do that ?
This code will only fetch the price details.
var obj = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var stringify = JSON.parse(obj);
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]['price']);
}
Observation :
If you want to parse the array of objects to get the property value you have to convert in into JSON object first.
DEMO
var jsonStringify = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var jsonObj = JSON.parse(jsonStringify);
for(var i = 0; i < jsonObj.length; i++)
{
alert(jsonObj[i]['price']);
}
you will geting a stringified object like this
var obj='[{"availability_id":"109465","date":"2017-02-21","price":"430000"},
{"availability_id":"109466","date":"2017-02-22","price":"430000"},
{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
parse your obj using JSON.parse(object)
then apply this loop ad let me know it get any error
lie this
var parseObject = JSON.parse(object);
instead of using stringify before selecting the data you should use your loop directly on the values array.
For example :
var priceArray = array();
values.forEach (data) {
alert(data['price'];
priceArray.push(data['price']);
}
stringify = JSON.stringify(values);
stringifiedPriceArray = JsON.stringify(priceArray);
Once stringified, you can't reach the data in your array

how to get values from json with unknown ammount of given elements

Given this json as example:
[
{"offspring0":"John"},
{"offspring1":"Anna"},
{"offspring2":"Peter"}
]
I can know how many offspring are there with:
offspringCount = (jsonString.match(/offspring/g) || []).length; //jsonString is the json above
This would return 3. Now, how can i get the value of all those offsprings? I have tried:
json = JSON.parse(jsonString);
alert(json[0].offspring[0]);
But this throws Uncaught TypeError: Cannot read property '0' of undefined because offspring is not an array.
I also tried:
alert(json[0]."offspring0");
But getting Uncaught SyntaxError: Unexpected string
My intention is to loop through all the offspring[number] and get the values, was expecting something like this:
for(x=0; x<offspringCount; x++){
alert(json[0].offspring[x]);
}
Note i do not handle the making of the JSON, i only request it to a server.
Try this:
var jsonString = '[{"offspring0":"John"},{"offspring1":"Anna"},{"offspring2":"Peter"}]';
var array = JSON.parse(jsonString);
var offsprings = [];
for (var i=0; i<array.length; ++i) {
for (var key in array[i]) {
if (key.match(/^offspring[0-9]+$/)) {
offsprings.push(array[i][key]);
}
}
}
document.getElementById('output').innerHTML = JSON.stringify(offsprings);
<div id="output"></div>
I thing this code may help you
json = JSON.parse(jsonString);
alert(json[0]['offspring0']);
this means, when you need to loop around your array , you need to do something like this:
for(var index = 0; index < json.length; index++) {
alert(json[index]['offspring' + index]);
}

return data of a field in store in array

This might be a question of pure javascript but somehow I cant get this right. I am working on extjs4.2 using sencha architect. I have a json response sent from server as
{
"data": [{
"ExamID": 1,
"ExamName": "Semester-1",
"MaxMarks": 100
}, {
"ExamID": 4,
"ExamName": "Test-1",
"MaxMarks": 10
}, {
"ExamID": 5,
"ExamName": "Test-2",
"MaxMarks": 10
}]
}
what I am looking for is to reconfigure grid using the data of "ExamName" only. So "ExamName" shall be passed as array in reconfigure() function.
I am unable to get "ExamName" in array form. Your help is highly appreciated
var gridStore = Ext.data.StoreManager.get('ClassSemesterStore');
var g = gridStore.load( {params : {ClassID: ClassData }});
var data = g.data;
var length = data.getCount();
var examName = [];
for(var i = 0; i < length; i++){
examName.push(data[i]['ExamName']);
}
it says "Uncaught TypeError: Cannot read property 'ExamName' of undefined"
I think if I understand you correctly, you're trying to have examName be a new array with it's contents being each ExamName in your response data? If so, this should work.
var data = {"data":[{"ExamID":1,"ExamName":"Semester-1","MaxMarks":100},{"ExamID":4,"ExamName":"Test-1","MaxMarks":10},{"ExamID":5,"ExamName":"Test-2","MaxMarks":10}]}
var examName = [];
for(var i = 0; i < data.data.length; i++){
examName.push(data.data[i]['ExamName']);
}
now examName is an Array with "Semester-1", "Test-1", and "Test-2"
Store's data in not an array. It's a Mixed Collection I think. So either use the following:
var examName = [];
for(var i = 0; i < length; i++){
examName.push(data.items[i].data['ExamName']);
}
or better yet get the information from your source like the people suggested.
Another good alternative is Store's collect.
You can do sth like:
gridStore.collect('ExamName')
The error was because of asynchronous nature of store loading:
var g = Store.load({
params : {ClassID: ClassData },
callback : function(records, operation, success){
var Excerpt = []; // start with empty array
Ext.each(records, function(item) {
// add the fields that you want to include
var Obj = {
third_field: item.get('ExamName')
};
Excerpt.push(Obj); // push this to the array
}, this);
console.log(Excerpt);
}
});

JS code returning error

I'm new to JS and i had to use it for Cloud Code Parse feature. I have a class called "user_picture", through the code i query all the objects and go through it's "City" attribute. i want the response to be an array of unique city names. Anyway, here is the code i'm working on:
Parse.Cloud.define("cities", function(request, response) {
var query = new Parse.Query("user_picture");
query.find({
success: function(results) {
var cities = new Array();
for (var object in results){
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
response.success (cities);
}, error: function() {
response.error("Error");
}
});});
However, when i run this function i receive the following error:
Error: TypeError: Object 0 has no method 'get'
at query.find.success (main.js:15:30)
at Parse.js:2:5786
at r (Parse.js:2:4981)
at Parse.js:2:4531
at Array.forEach (native)
at Object.E.each.E.forEach [as _arrayEach] (Parse.js:1:666)
at n.extend.resolve (Parse.js:2:4482)
at r (Parse.js:2:5117)
at Parse.js:2:4531
at Array.forEach (native) (Code: 141, Version: 1.2.18)
And the response returns null. I tried printing one object from the results array in order to make sure i'm receiving the right query, and it's printing fine the city. What could be the problem?
The for in loop iterates through all the keys of an object literal. Since results is an Array it will iterate through the keys of the Array, which are '0', '1' etc.
This means that the object variable will hold those key vales. And since they are not objects they don't have a method called get.
You need a forEach loop instead.
results.forEach(function(object){
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
});
Or if you're targeting ES3 then you should use a for loop
for(var i = 0, length = results.length; i< length; i++){
var object = results[i];
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
I recall working with Parse objects a bit and there seemed to be times to access them as an object (by direct parameter access) and sometimes by using the get method and it looks like you're mixing up the array access and object (from Parse) access methods.
Also, your list generator doesn't seem like it's really building a unique list. You only check to see if the current city is the same as the city you're going to add.
I might do something more like this (for the success method):
function(parseResults) {
var cities = {};
var ii=0;
var nResults = parseResults.length
for(;ii<nResults;++ii) {
cities[result.get('city')] = 1
}
var citiesArray = cities.keys();
response.success(citiesArray);
}
What we do here is build up an object whose keys are city names. Then return the keys as an array. What this does for us is automatically build a unique list because object keys should be unique.
If the result.get gives you problems, try replacing it with result.city. But i suspect the error you were seeing with your first example was trying to call get on the Array element.

Looping through nested arrays in Javascript

So I have an API that returns JSON data
Example JSON:
{
"result":"OK",
"data":[
{
"number":"613-555-5555",
"calls":30
},
{
"number":"613-666-5555",
"calls":100
}
]
}
I am trying to output this using javascript to show the following
[number, calls],[number, calls]
var response = response.data;
var length = response.length;
alert(data[0].number);
alert(data[0].calls);
for (var i = 0; i < data.length; i++) {
var arrayItem = data[i];
document.write(arrayItem);
}
This is simply a question of mapping your data to the desired format:
var final = response.data.map(function(item) {
return [item.number, item.calls];
});
console.log(final);
Here is a demo: http://jsfiddle.net/c8UQg/
EDIT:
I didn't realise you were looking for a string representation (I thought you wanted an array). If that is the case, please disregard the above.
If you like everything the way it is code wise, and just want to fix the error, then I suggest changing
var response = response.data;
to
var data = response.data;
Also, for the sake of debugging, change
document.write(arrayItem);
to
console.log(arrayItem);
http://jsfiddle.net/GptRW/

Categories

Resources