I'm trying to display data after a Fetch. I grouped this data by date so I grouped my objects into an array which have the date as main key.
But now, I'm kind of lost and don't know how to display get the date as Header section then the objects.
This is my data:
"31 janvier 2015": Array [
Object {
"image": "image",
"name": "name",
},
Object {
"image": "image",
"name": "name",
},
],
"02 février 2016": Array [
Object {
"image": "image",
"name": "name",
},
Object {
"image": "image",
"name": "name",
},
]
What I would like to do is to display it like a section list :
31 janvier 2015
> object
> object
02 février 2016
> object
> object
I think I can map the objects but first I have to get the date and go inside that array.
What you have is an associative array, that is an array that instead of numeric indexes has strings. It works just like an object would if you were for example to do person['age'] on a person object.
You can loop through the "indexes" with the below code, checking hasOwnProperty to avoid any inherited properties. You can then access your dates by key
for (var key in MainArray) {
if (MainArray.hasOwnProperty(key))
console.log(MainArray[key]);
}
Iterate over the map keys, displaying the date and listing the items.
for(let date in list){
// Date as SECTION HEADING
console.log(date);
// access items...
const items = list[date];
// Display item
items.forEach(console.log);
}
Related
I have an array that contains objects, like this:
"exams": [
{
"id": "62b30836e941368db5d0e531",
"name": "Basic",
"price": 100
},
{
"id": "62b30836e941368db5d0e532",
"name": "Full",
"price": 200
}
]
I need pick only the name property from every object, and build a string, where the elements are "separated" with comma.
Like this:
"Basic,Full"
I tried the following, but the method built every whole object into the string:
var e = exams.join(",");
Before using the .join() to create a string, you should map the values you want from the array of objects. Like this:
exams.map(exam => exam.name)
This should return something like: ['Basic', 'Full'].
Then you do the join.
You could do all in one line (also avoid var, use const instead):
const e = exams.map(exam => exam.name).join(',')
I'm making a little app in nodejs, I'm struggling trying to print some data provenient from a json which has the following structure:
{
"courses": [
{
"java": [
{ "attendees": 43 },
{ "subject": "Crash course" }
]
},
{
"python":
{
"occurrences": [
{ "attendees": 24 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
,
{ "attendees": 30 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
]
}
}
],
}
If I want to print the attendees at 'java' I do:
console.log(myJSON.courses[0]['java'][0]['attendees']);
which prints
43
and if I want to print the notes of the 2nd occurrence of the python course I do:
console.log(myJSON.courses[1]['python']['occurrences'][2]['notes']);
which prints:
completed with issues
The before mentioned cases are correct, but what I want to do is to print the keys of 'java' ('attendees' and 'subject'), as you can see Java is an array and in its unique position it has two json objects, I've tried with:
console.log(myJSON.courses[0]['java'][0].keys;
and with
console.log(myJSON.courses[0]['java'].keys;
but they print "undefined" and "[Function: keys]" respectively.
What I'm missing here?
Could anybody help me please?:(
myJSON.courses[0]['java'] is an array with indexes. Where each index holds an object with keys. Your array doesn't exactly have the keys you want (the keys of an array are its indexes: 0, 1 etc...)
Instead, you want to access all the keys from the objects in the myJSON.courses[0]['java'] array.
You can do this by using .map and Object.keys. .map will allow you to get and convert every object in your myJSON.courses[0]['java'] array. Object.keys() will allow you to get an array of keys from the given object (in your case your array will be of length 1, and so you can access index 0 of this array).
const myJSON = {courses:[{java:[{attendees:43},{subject:"Crash course"}]},{python:{occurrences:[{attendees:24},{subject:"another crash course"},{notes:"completed with issues"},{attendees:30},{subject:"another crash course"},{notes:"completed with issues"}]}}]};
const myKeys = myJSON.courses[0]['java'].map(obj => Object.keys(obj)[0]);
console.log(myKeys);
If you have multiple keys in your objects within an array, you can also use .flatMap (take note of browser support):
const myJSON = {courses:[{java:[{attendees:43},{subject:"Crash course"}]},{python:{occurrences:[{attendees:24},{subject:"another crash course"},{notes:"completed with issues"},{attendees:30},{subject:"another crash course"},{notes:"completed with issues"}]}}]};
const myKeys = myJSON.courses[0]['java'].flatMap(Object.keys);
console.log(myKeys);
Modifying a JSON array (nested into another array) seems NOK with this code:
var names = [{'name': 'ourname'},{'name': 'yourname'}] ;
var array = [{
"year": "2015",
names
},{
"year": "2016",
names
}];
I can't modify a single name entry in "array" by doing this
array[0].names[1].name="MY NAME"
since it's actually modifying all names entry in the row "0":
Output:
0:0 ourname
0:1 MY NAME
1:0 ourname
1:1 MY NAME
Plunker here
I'm looking for a clean way to achieve a proper single modification in the name array as I'd like to avoid loops to do this.
Thanks for your help
Because they're pointing to same array, and also, simply clone names by .slice is not enough, as the array contains objects not primitive types, so you need to deep clone from the original names and assign to each object.
So you need to change the code to :
var array = [{
"year": "2015",
names: JSON.parse(JSON.stringify(names))
}, {
"year": "2016",
names: JSON.parse(JSON.stringify(names))
}];
See the edited pluker.
I use JSON.parse(JSON.stringify(names)) to simply create do deep clone from original array here, there can have other ways.
You should try copying the names array, once for each "unique" use case, since Javascript sneakily has references sometimes.
One way to do it is to write a deepclone() method that will do a deep copy of a hierarchical object.
var array = [{
"year": "2015",
names: deepclone(names)
},{
"year": "2016",
names: deepclone(names)
}];
You need a key: value in an object (javascript object).
var names = [{'name': 'ourname'},{'name': 'yourname'}] ;
var array = [{
"year": "2015",
"names": names
},{
"year": "2016",
"names": names
}];
var wName = array[0].names[1].name;
// yourname
I'm trying to create a JSON object with a nested array of JSON objects. What is the correct format of this?
Here is an example what I am trying to create:
{
"reviewCount": 96,
"reviews": [
{"name": "Sean Steinman", "date": "reviewed 2 weeks ago", "reviewContent": "Fantastic Service"},
{"name": "Ryan Lundell", "date": "reviewed in the last week", "reviewContent":"Ask for Scott!"}
]
}
Here is what I have so far:
var reviewObj = {
reviewCount: reviews.length,
reviews: [{name: , date: , reviewContent:}]
}
After I initialize it, I will fill it with a for loop that runs through an existing array of strings.
CLARIFICATION:
The array that I'm using to populate the JSON object is:
[
"\nSean Steinman\nreviewed 2 weeks ago\n Fantastic Service\n",
"\nRyan Lundell\nreviewed in the last week\n Ask for Scott!\n• • •\n"
]
So I'm creating a new array in my for with tmpArr = reviews[i].split('/n');, and then where I'm getting stuck is how to stick that into the JSON object as an object.
First, you're not building a "JSON" object. You're just building an object. It's not JSON until you JSON-encode it. {"name": "bob"} is not JSON, it's an object literal. '{"name": "bob"}', the string, is JSON.
Second, you cannot loop inside an object literal, which is what your second code example seems to indicate you're trying to do. Instead, you need to initialize you reviews property to an empty array, and then loop and append items to the array.
var reviews = [
"\nSean Steinman\nreviewed 2 weeks ago\n Fantastic Service\n",
"\nRyan Lundell\nreviewed in the last week\n Ask for Scott!\n• • •\n"
];
var reviewObj = {
reviewCount: reviews.length,
reviews: []
}
reviews.forEach(function(line) {
var review = line.split("\n");
reviewObj.reviews.push({name: review[0], date: review[1], reviewContent: review[2]});
});
NOTE: Language i am using is Javascript
I have a an array of objects. Each object has three properties: year, date, title.
For example:
[
{
year: 2013, date: "23/10/2013", title: "Title1"
},
{
year: 2012, date: "4/2/2012", title: "Title2"
}
]
I need to make an efficient data structure from this array such that:
All objects with same year are grouped together, and groups are sorted on the basis of "year"
All objects with same date and title are grouped together. Objects with different dates are sorted.
The data structure should be efficient for reading and traversing (i need to present them in some sort of timeline).
So, you probably want something like this:
var objects = {
"2012":{
"4/2/2012":{
"title1":[
//array of objects
],
"title2":[
//array of objects
],
// etc
},
"5/9/2012":[
"title3":[/*objects*/],
],
},
"2013":{
// etc
}
}
Then you can just access the array of objects them like this:
objects["2012"]["5/9/2012"]["title1"]
So:
objects["year"]["date"]["title"];