How would you go about iterating through a JSON object no initial key but multiple entries?
var json_no_key =
{
{"txid" : "1",
"amount" : "100",},
{"txid" : "2",
"amount" : "50"},
};
I have tried using other methods whereby each element would have a key itself such as
for(var i = 0; i < transaction.vin.length; i++)
{
var my_json = transaction.vin[i];
console.log(my_json[i])
for(var j = 0; j < my_json.length; j++)
{
console.log(my_json[j]);
}
}
but this relies on there being an initial key.
The reasoning for this format is due to the nature of how a api outputs data.
I echo with #CherryDT. The object json_no_key is not a valid JSON format. Please check the format in https://jsonlint.com/. Instead of an object, convert it into an array so that you could do the following using a simple forEach:
const a =[
{
"txid": "1",
"amount": "100",
},
{
"txid": "2",
"amount": "50"
},
];
a.forEach(element=>{
console.log(element.txid);
console.log(element.amount);
})
Related
I am facing an issue in small requirement. I want to create a JSON array in below format using JavaScript for loops.
var payloadTest = {
"people": [{
"pic": "sap-icon://employee",
"name": "Ravi",
"role": "team member",
"appointments": [{
"start": new Date("2017", "0", "21", "0", "0"),
"end": new Date("2017", "0", "21", "23", "59"),
"title": "Meet John Miller"
}, {
start: new Date("2017", "0", "18", "0", "0"),
end: new Date("2017", "0", "18", "23", "59"),
title: "Team meeting",
}]
]
}
};
Im trying with below code using for loops. But it is not working.
var itemsArr = [];
var headArr = [];
for (var i = 0; i < resultSet.length; i++) {
var obj = {};
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
headArr.push(itm);
obj.start=resultSet[i].Begda;
obj.end=resultSet[i].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
//headArr.push(itemsArr);
}
payloadTest.people = headArr;
payloadTest.people.appointments = itemsArr;
Can someone please help me to create an array using for loops in the above JSON Format.
Note :: appointments array count may increase based on the results coming from backend
In:
payloadTest.people.appointments = itemsArr;
you are trying to assign the appointment array as a property of an array of people. Instead, you should be assigning it as a property of an (or every?) individual person.
So you could do:
payloadTest.people[0].appointments = itemsArr;
but that would only give one of the people an array of appointments. It's unclear from your code whether you want each person to have a reference to (or copy of) the same appointment array, one person to have it, or whether you thought you were creating separate arrays for each person. To do the later, you'd need a nested loop.
Update
You probably want to move the declaration/initialization of itemsArr inside the loop, so that each person has their own array (otherwise, modifications to one person's appointment array would be made to everyone's array).
Then, you would likely want to initialize them with a unique test array - so a nested loop (say j from 0 to i), creating incrementally larger lists of appointments for each person. But as it's just test data you're creating, it's really up to you what belongs in there.
Change your code according to below code
for (var i = 0; i < resultSet.length; i++) {
var obj = {};
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
headArr.push(itm);
obj.start=resultSet[i].Begda;
obj.end=resultSet[i].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
itm.appointments = itemsArr; // Added
//headArr.push(itemsArr);
}
payloadTest.people = headArr;
/*payloadTest.people.appointments = itemsArr;*/ // Removed
Removed
payloadTest.people.appointments = itemsArr;
Because it assigns appointments to person array not to each person. You have to add appointments to each person record to added in loop
itm.appointments = itemsArr;
See below snippet for your multiple appointment. I used dummy data.
Change according to your data format.
var headArr = [];
var payloadTest = [];
var resultSet = [{'Rowlabel' : 'Ravi', 'RowId' : 'team member', 'appointments' :[{'Begda' : 'test', 'Endda' : '1'}, {'Begda' : 'test', 'Endda' : '1'}]}, {'Rowlabel' : 'name', 'RowId' : '1', 'appointments' : [{'Begda' : 'test', 'Endda' : '1'}]}];
for (var i = 0; i < resultSet.length; i++) {
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
var itemsArr = [];
for (var j = 0; j < resultSet[i].appointments.length; j++) {
var obj = {};
obj.start=resultSet[i].appointments[j].Begda;
obj.end=resultSet[i].appointments[j].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
}
itm.appointments = itemsArr; // Added
headArr.push(itm);
}
payloadTest.people = headArr;
/*payloadTest.people.appointments = itemsArr;*/ // Removed
console.log(headArr);
Hope it helps.
I have this array:
recentPageArray = {
"e49f8a67-3075-433a-bacd-30379008fdb2": {
"id": "e49f8a67-3075-433a-bacd-30379008fdb2",
"name": "afolder",
"type": "indexfolder"
},
"3a1ca419-5467-4662-9f7a-f3e9246a1d49": {
"id": "3a1ca419-5467-4662-9f7a-f3e9246a1d49",
"name": "folder1",
"type": "indexfolder"
},
"832f9d4e-297e-40e9-9189-75ce3b86341a": {
"id": "832f9d4e-297e-40e9-9189-75ce3b86341a",
"name": "afolder",
"type": "documentfolder"
},
"86fee1ce-21cd-4948-bf9d-a6c81b897a0e": {
"id": "86fee1ce-21cd-4948-bf9d-a6c81b897a0e",
"name": "afolder",
"type": "documentfolder"
}
}
Whenever I push new array in the this array. Key sort automatically. I dont want to sort array in the key base. I need new pushed key item in top of the array.
I suggest you to mantain 2 references:
1 Array (list)
1 Object (key, value)
The Object (key->val) cannot mantain the elements' insert order (and if an utopic new browser implementation want to order in descending order(for any cause) your code will be sensible to it).
So, while populating the object,also push the element key in the Array.
When you want to iterate use the Array to iterate in order (and it is also faster)
myObject = {};
myArray = [];
/** POPULATING **/
for (var x in myData){
myObject[myData[x].key] = myData[x].value;
myArray.push(myData[x].key);
}
/** ITERATING **/
for (var y =0; y < myArray.length; y++){
var readingKey = myArray[y];
var storedData = myObject[readingKey];
//your code here
}
Regards
I have some JSON data being returned from an AJAX call. I then need to parse this data in javascript.
The data looks like so:
[
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
]
Why is it when i run this code on the data that i get multiple undefined's?
(var json being the variable holding my json data)
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.id);
}
However if i assign the json directly to the variable like so:
var json = [
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
];
Then it works fine!
Any ideas guys? Thanks
Make sure the JSON you're getting is not just stringified JSON. In that case do JSON.parse(json_string) and then loop and more processing.
Example:
var string_json = '[{"a":1},{"b":2}]'; // may be your API response is like this
var real_json = JSON.parse(string_json); // real_json contains actual objects
console.log(real_json[0].a, real_json[1].b); // logs 1 2
It is not a JSON that, you are using.
It's an object array.
When you get JSON, parse that JSON using method JSON.parse.
Assign this JSON to a variable and then use iteration over it...
Ex:
var json ='[{"id": "23","date_created": "2016-05-12 14:52:42"},{"id": "25","date_created": "2016-05-12 14:52:42"}]';
var parsedJson = JSON.parse(json);
for(var i = 0; i < parsedJson.length; i++) {
var obj = parsedJson[i];
console.log(obj.id);
}
Okay so I'm using angular to get a json saved to my computer to recreate a github gradebook.
I can get the data with my $http request but for the love of me all I want is to get a count of the number of issues with the label "Not Yet".
Here is the javascript:
$http.get('/api/github/repos/issues/all_issues/00All.json')
.then(function(response) {
console.log(response.data[0]);
var counter = 0;
for(var index = 0; index < response.data.length; index++) {
if(response.data[index].labels[0].name == "Not Yet") {
counter++;
};
};
console.log(counter);
});
That's the latest try, I also tried using lodash to get it earlier:
$http.get('/api/github/repos/issues/all_issues/00All.json')
.then(function(response) {
console.log(response);
mile.notYet.width = _.forEach(response.data, function(n){
var counter = 0;
if(_.result(_.find(n.labels[0], 'name')) == "Not Yet") {
counter++;
}
console.log(counter);
counter = ((counter/10) * 100) + '%';
});
});
This is a bit of the json data:
[
{
"url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11",
"labels_url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11/labels{/name}",
"comments_url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11/comments",
"events_url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11/events",
"html_url": "https://github.com/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11",
"id": 73013825,
"number": 11,
"title": "00 -- Brace Yourself -- BEN GRIFFITH",
"user": {
"login": "Epicurean306",
"id": 11682684,
"avatar_url": "https://avatars.githubusercontent.com/u/11682684?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/Epicurean306",
"html_url": "https://github.com/Epicurean306",
"followers_url": "https://api.github.com/users/Epicurean306/followers",
"following_url": "https://api.github.com/users/Epicurean306/following{/other_user}",
"gists_url": "https://api.github.com/users/Epicurean306/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Epicurean306/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Epicurean306/subscriptions",
"organizations_url": "https://api.github.com/users/Epicurean306/orgs",
"repos_url": "https://api.github.com/users/Epicurean306/repos",
"events_url": "https://api.github.com/users/Epicurean306/events{/privacy}",
"received_events_url": "https://api.github.com/users/Epicurean306/received_events",
"type": "User",
"site_admin": false
},
"labels": [
{
"url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/labels/Not%20Yet",
"name": "Not Yet",
"color": "e11d21"
}
],
As you can see the labels property is an object, nested in an array, nested in an object, nested in an array, real lovely. Putting labels[0] results in an error for me each time and doesn't get me a count. Can anybody tell me where I'm messing up please? Thank you!
If you need a solution that includes lodash, which is much more performant than the native high order functions then you can try this solution below:
var size = _(response.data)
.pluck('labels')
.flatten()
.where({ name: 'Not Yet' })
.size();
UPDATE:
If you want it to be more reusable, you can save a reference for a cloned chained sequence and simply supply another array for that cloned sequence.
var data1 = [/*array from data1*/];
var data2 = [/*array from data2*/];
var notYetSequence = _(data1)
.pluck('labels')
.flatten()
.where({ name: 'Not Yet' });
notYetSequence.size(); // returns data 1 count
notYetSequence.plant(data2).size(); // returns data 2 count
You don't need lodash for the task
var cnt = response.data
.map(function(i) { return i.labels; })
// here we extract labels object only (and get an array of arrays of objects)
.map(function(i) { return i.filter(function(l) { return l.name == 'Not yet'; }).length; })
// then for every nested array we return a number of items with
// Not Yet names (and get an array of numbers)
.filter(function(c) { return c > 0; })
// then we filter issues that don't have one (and still get an array of numbers)
.length;
// and finally get length (which is a number)
As a comparison, a plain for loop looks like:
var data = response.data;
var count = 0;
var re = /not yet/i;
for (var a, i=0, iLen=data.length; i<iLen; i++) {
a = data[i].labels;
for (var j=0, jLen=a.length; j<jLen; j++) {
if (re.test(a[j].name)) ++count;
}
}
So really not a lot of code either way, the for loop will be compatible with every browser ever (though using xmlHTTPRequest means at least ed 3+) and fastest… untested of course. ;-)
I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");