I need assistance in accessing a nested array located my JSON Data Set. Here is the first entry of my top-level JSON array:
{
"pingFeed": [{
"header": "Get Drinks?",
"picture": "images/joe.jpg",
"location": "Tartine's, SF",
"time": "Tomorrow Night",
"name": "Joe Shmoe",
"pid":
"123441121",
"description": "Let's drop some bills, yal!",
"comments": [{
"author": "Joe S.",
"text": "I'm Thirsty"
},
{
"author": "Adder K.",
"text":
"Uber Narfle"
},
{
"author": "Sargon G.",
"text": "taeber"
},
{
"author": "Randy T.",
"text": "Powdered Sugar"
},
{
"author": "Salvatore D.",
"text":
"Chocolate with Sprinkles"
},
{
"author": "Jeff T.",
"type": "Chocolate"
},
{
"author": "Chris M.",
"text": "Maple"
}],
"joined": false,
"participants": [
"Salvatore G.", "Adder K.", "Boutros G."],
"lat": 37.25,
"long": 122,
"private": true
}]
}
I would like to know how I can access the comments and participants data using the following notation:
for (var k = 0; k < pingFeed.length ; k++) {
console.log(pingFeed[k].comments);
console.log(pingFeed[k].participants);
}
Currently this form of dot notation is working for the other entries in the JSON array...
I am looking to return all of these data as Strings.
I'm not sure quite what you're looking to do, but perhaps this will point you in the right direction:
for (var k = 0; k < pingFeed.length; k++) {
for (var i = 0; i < pingFeed[k].comments.length; i++) {
var oComments = pingFeed[k].comments[i];
console.log( oComments.author + ": " + oComments.text );
}
console.log(pingFeed[k].participants.join(", "));
}
Well, comments and participants are arrays, so you can access them like normal arrays, e.g.:
for (var k = 0; k < pingFeed.length ; k++) {
var comments = pingFeed[k].comments;
for(var i = 0, length = comments.length; i < length; ++i) {
console.log(comments[i]);
}
}
There's nothing wrong with your code: pingFeed[k].comments will return array and pingFeed[k].comments[0] will return first comment from that array.
Try here
http://jsfiddle.net/U8udd/
Related
i want to read the value "name" or "count".
"facet_groups": [
{
"facets": [
{
"count": 233,
"path": "75011",
"state": "displayed",
"name": "75011"
},
{
"count": 180,
"path": "75015",
"state": "displayed",
"name": "75015"
},
This is my code :
LoadData(request)
.then(function(response){
console.log(response);
let facet = response.facet_groups;
for(let i=0; i<50; i++){
let arrondisement = facet[i].facets[i].name;
console.log(arrondisement);
}
When i try this i have this message : "OpenDataParis.js:43 TypeError: Cannot read property 'facets' of undefined"
it need multiple loop and to avoid error it better to use array.length instead fixed number.
let response = {
"facet_groups": [{
"facets": [{
"count": 233,
"path": "75011",
"state": "displayed",
"name": "75011"
},
{
"count": 180,
"path": "75015",
"state": "displayed",
"name": "75015"
}
]
}]
}
let facet_groups = response.facet_groups;
for (let i = 0; i < facet_groups.length; i++) {
for (let j = 0; j < facet_groups[i].facets.length; j++) {
let name = facet_groups[i].facets[j].name;
let count = facet_groups[i].facets[j].count;
console.log("for:", name, count);
}
}
facet_groups.forEach(function(item) {
item.facets.forEach(function(facet) {
console.log("forEach:", facet.name, facet.count)
})
})
You were missing that your array actually starts within object index[0] and that you need to loop through the facets array not the facet groups array. If you want to loop through both I would nest a couple for loops following this example:
data = {
"facet_groups": [
{
"facets": [
{
"count": 233,
"path": "75011",
"state": "displayed",
"name": "75011"
},
{
"count": 180,
"path": "75015",
"state": "displayed",
"name": "75015"
}
]
}
]
}
let facets = data.facet_groups[0].facets;
let arrondisements = []
for(let i=0; i<facets.length; i++){
arrondisements.push(facets[i].name);
};
console.log(arrondisements);
var data = [
{
"text": "BEHIND A COMMON MEAL: POLYPHENOLS IN FOOD ",
"id": "445",
"parentid": ""
},
{
"text": "2.2 First Course: Pasta With Tomato Sauce (Polyphenols in Wheat Bran and Tomato Byproducts)",
"id": "441",
"parentid": "445"
},
{
"text": "2.3 A Fresh Side Dish: Mixed Salad (Polyphenols From Fennel, Carrot)",
"id": "442",
"parentid": "445"
},
{
"text": "hello mr.sujai",
"id": "448",
"parentid": "445"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "445"
},
{
"text": "INTRODUCTION",
"id": "452",
"parentid": ""
},
{
"text": "1.2 The Tight Biochemical Connection Between Vegetables and Their Byproducts",
"id": "440",
"parentid": "452"
},
{
"text": "OTHER OFF-THE-MENU MISCELLANEOUS",
"id": "454",
"parentid": ""
},
{
"text": "SOMETHING TO DRINK",
"id": "456",
"parentid": ""
},
{
"text": "3.1 Orange Juice (Polyphenols From Orange Byproducts)",
"id": "443",
"parentid": "456"
},
{
"text": "3.2 Wine (Polyphenols From Grape and Wine Byproducts)",
"id": "444",
"parentid": "456"
},
{
"text": "understandings",
"id": "451",
"parentid": "456"
},
{
"text": "Polyphenols",
"id": "453",
"parentid": "451"
},
{
"text": "this is test",
"id": "458",
"parentid": "455"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "458"
},
{
"text": "hello",
"id": "447",
"parentid": "449"
},
{
"text": "hi",
"id": "459",
"parentid": "447"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "459"
},
{
"text": "testing",
"id": "457",
"parentid": "458"
},
{
"text": "hi test",
"id": "450",
"parentid": "457"
},
{
"text": "speech",
"id": "446",
"parentid": "450"
}]
function jsonTree() {
// Keep a fast lookup dictionary
var dictionary = {};
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
}
for (var i = 0; i < data.length; i++) {
if (data[i].parentid == 449) {
var test = "";
}
if (data[i].parentid) {
var parent = dictionary[data[i].parentid];
arrData = parent;
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(data[i]);
// arrData.children.push(data[i]);
}
}
}
var arrData = [];
for (var i = 0; i < data.length; i++) {
if (data[i].parentid == 455) {
arrData.push(data[i]);
}
}
document.getElementById("test").innerHTML = JSON.stringify(arrData);
return false;
}
polyhierarchy term having different parent.
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
}
in this place same id is replaced. polyhierarchy having id is 449. when add to dictionary it is replaced.
Tree structure should be
1. BEHIND A COMMON MEAL: POLYPHENOLS IN FOOD
polyhierarchy
2. this is test
polyhierarchy
hello
hi
polyhierarchy
i need array with parent, child relationship.
There are a few mistakes.
You have duplicate id's for your polyhierarchie element. Because you're building a dictionary to lookup your ids, you're overwriting your child element the second/subsequent time you add it to your object.
{
"text": "polyhierarchy",
"id": "449", //<-- duplicate
"parentid": "459"
}
You have non existant parentIds.
{
"text": "SOMETHING TO DRINK",
"id": "456",
"parentid": "455" // <--- doesn't exist
}
The code got a little more complex than anticipated because of those two issues.
function mapData (data) {
//build a dictionary for: id -> [eles]
var map = data.reduce ((obj, ele) => {
obj[ele.id] = [ //let's make the lookup an array, to support multiple elements with the same id
...obj[ele.id] || [], //keep the existing elements or initialize it to an array
{...ele, children: []}
];
return obj
}, {});
return Object.keys (map).reduce ((arr, key) => {
let eles = map [key] || []; //process all elements
eles.forEach (ele => {
let parents = map [ele.parentid] || [];
let parent = parents [0];
if (!parent) {
parent = map [ele.parentid] = {children: [], root: true}
}
parent.children.push (ele);
if (parent.root && !~arr.indexOf (parent)) arr.push (parent);
});
return arr;
},[])
}
console.log (mapData (data))
More or less the situation is like this: I get an array (using JS) and one object (let's call it TASK) looks like this (it's not the full array, just ONE instance):
{
"id": "28",
"name": "sdfsdf",
"progress": 80,
"description": "",
"code": "1",
"level": 1,
"status": "STATUS_SUSPENDED",
"depends": "",
"canWrite": true,
"start": 1444341600000,
"duration": 7,
"end": 1445291999999,
"startIsMilestone": 0,
"endIsMilestone": 0,
"collapsed": false,
"assigs": [
{
"resourceId": 3,
"otherStuff": xyz
},
{
"resourceId": 2,
"otherStuff": xyz
}
],
"hasChild": true
}
The other object that I load contains all "resources", referred in the first array with "assigs": [] (let's call these RESOURCES):
[
{
"ID": "1",
"name": "service | 1st resource we need",
"unit": "pcs",
"quantity": "10"
},
{
"ID": "2",
"name": "money | Office space",
"unit": "hour",
"quantity": "50"
},
{
"ID": "3",
"name": "product | Money for nothing...",
"unit": "$",
"quantity": "300"
},
{
"ID": "4",
"name": "people | Chovjek",
"unit": "people",
"quantity": "1"
}
]
I populate some form fields with task data, but there is simply no way I can figure out how to "connect" the task with its resources.
Like this if we are talking newer versions of javascript:
for(var task of tasks)
{
for(var ass of task.assigns)
{
for(var res of resources)
{
if(res.ID === ass.resourceId.toString()) {
//here res and ass match and you can do what you want
}
}
}
}
In all versions of JS you can do it like this
for(var i = 0; i < tasks.length; i++)
{
for(var x = 0; x< tasks[i].assigns.length; x++)
{
for(var y = 0; y < resources.length; y++)
{
if(resources[y].ID === tasks[i].assigns[x].resourceId.toString()) {
//here res and ass match and you can do what you want
}
}
}
}
This might not be the best answer there is, but I'd probably use the the filter().
You loop through all your tasks (in a foreach loop for instance), and then you loop through each assig(?), and then do:
for (var task of tasks) {
for (var currentAssig of assigs) {
var resourceId = currentAssig.resourceId;
var relevantResource = RESOURCES.filter(function (res) {
return res.ID === resourceId;
});
// do whatever you want with your resource.
}
}
What if instead of "resourceId" you just set your Resource object in there?
You will have your connection:
{
"id": "28",
"name": "sdfsdf",
/* .... */
"assigs": [
{
"resource":
{
"ID": "1",
"name": "service | 1st resource we need",
"unit": "pcs",
"quantity": "10"
},
"otherStuff": xyz
},
{
"resource":
{
"ID": "2",
"name": "service | 2nd resource we need",
"unit": "pcs",
"quantity": "20"
},
"otherStuff": xyz
}
],
"hasChild": true
}
Or, if you want to keep your structure, just add a reference to object that exists in the Resources array:
"assigs":
[
{
"resourceId": 3,
"resource": yourResourceArray[0], //<-- [0] for sake of simplicity
"otherStuff": xyz
},
{
"resourceId": 2,
"resource": yourResourceArray[1], //<-- [1] for sake of simplicity
"otherStuff": xyz
}
],
I'm not sure whether or not this is what you're looking for, but you should be able to loop through the Task array, and inside that loop, loop through the assigs array, and inside this loop, loop through your Resources array. Doing this, you can find the connection.
Example:
//Loop through Task array
for(i = 0; i < Task.length; i++){
//Loop through your assigs within the Task array, at the given index 'i'
for(j =0; j < Task[i].assigs; j++){
//Now loop through the Resources array, to find the ID that matches the assigs 'resourceId'
for(k =0; k < Resources.length; k++){
if(Task[i].assigs[j].resourceId === Resources[k].ID){
//You have the connection
}
}
}
}
NOTE: this could probably be optimized fairly much, but at least here's the principal
EDIT: or as Christian Nielsen does, using a foreach loop
Given the below response, how would I get things like title?
jsonFlickrFeed({
"title": "Thing",
"link": "http://www.flickr.com/photos/tags/",
"description": "",
"items": [
{
"title": "Title",
"link": "http://www.flickr.com/photos/123",
"media": {"m":"http://farm6.staticflickr.com/123.jpg"},
},
{
"title": "Title2",
"link": "http://www.flickr.com/photos/1234",
"media": {"m":"http://farm6.staticflickr.com/1234.jpg"},
},
})
I want to do something like:
for (var i=0; i<xml.responseText.length;i++) {
var x = (xml.responseText.items.title[i]);
document.write(x)
}
What am I doing wrong here?
assuming xml.responseText is not null and is the defined result of the function in your question...
reference the responseText.items length, not responseText. Then move your index from title to items:
for (var i=0; i < xml.responseText.items.length; i++) {
var x = xml.responseText.items[i].title;
document.write(x)
}
I have an array of objects, which has an array of 'tracks.' What I would like to do is compare the mbid values across all of the track objects, check if there are any duplicates, and store the duplicate track objects into a new array. Any help or guidance?
[
{
"track": [
{
"name": "Radiapathy",
"mbid": "4c0767f1-1c2e-4790-a8d1-ee7f78f0ac84",
"url": "http://www.last.fm/music/The+Velvet+Teen/_/Radiapathy"
},
{
"name": "How Did I Get Here",
"mbid": "64b3078f-89cd-4ad5-bc7a-b43af082b00f",
"url": "http://www.last.fm/music/Odesza/_/How+Did+I+Get+Here"
},
{
"name": "Sunshine Roof",
"mbid": "837db975-c93e-45ca-992c-0c924ef0f34f",
"url": "http://www.last.fm/music/The+Innocence+Mission/_/Sunshine+Roof"
}
]
},
{
"track": [
{
"name": "Traveling",
"mbid": "b40c24b8-3295-4219-af59-855b69958ca2",
"url": "http://www.last.fm/music/Tennis/_/Traveling"
},
{
"name": "Ghost",
"mbid": "6273ae8f-3d2c-44c6-8c0d-53013ba79b4e",
"url": "http://www.last.fm/music/Neutral+Milk+Hotel/_/Ghost"
},
{
"name": "Strange",
"mbid": "5a015df2-6c4a-4192-bea8-14ec5f297713",
"url": "http://www.last.fm/music/Built+to+Spill/_/Strange"
}
]
},
{
"track": [
{
"name": "Radiapathy",
"mbid": "4c0767f1-1c2e-4790-a8d1-ee7f78f0ac84",
"url": "http://www.last.fm/music/The+Velvet+Teen/_/Radiapathy"
},
{
"name": "Let Me Show You Love",
"mbid": "",
"url": "http://www.last.fm/music/Cut+Copy/_/Let+Me+Show+You+Love"
},
{
"name": "Footsteps",
"mbid": "",
"url": "http://www.last.fm/music/Cut+Copy/_/Footsteps"
}
]
}
]
The answer to this question (Elminating duplicates in a JSON object) pretty much answers yours. I've used this (the "Smart(er) way") and modified to suit your array & requirements:
var key = null;
var noDupes = [];
var dupes = [];
for (var i = 0; i < arr.length; i++)
{
// loop through each track:
for (var j = 0; j < arr[i].track.length; j++)
{
key = arr[i].track[j].mbid;
if (!hash.contains(key))
{
hash.add(key);
noDupes.push(arr[i].track[j]); // if not duplicate
}
else
{
dupes.push(arr[i].track[j]); // if duplicate
}
}
}
http://jsfiddle.net/6wspy/