Related
Good time, i have an array of objects like this:
var sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];
So, for example, i want to get label that is for key=12 (it have to be Dolores Black). If i use something like:
alert(sections[11]['label']);
this will be wrong, cause it will find 12th element of array, not an element with key=12. So what is th right expression for my case? Thanks
Use Array#find:
let sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];
let res = sections.find(({key}) => key === 12)?.label;
console.log(res);
If you know that the element is nth in the array, use sections[n - 1]['label']; for example, to get Dolores Black (the 3rd element), you'd do:
sections[2]['label']; // 3 - 1 = 2
If you don't know the position of the element beforehand, you have to give some condition to JavaScript, so that it can find it; in your case, the condition is item.key === 12:
sections.find((item) => item.key === 12)['label'];
Note that in both cases we assume that the element actually exists in the array (if it doesn't, there will be errors).
The find() method which will return the value of the first element in the provided array that satisfies the provided testing function
var sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];
var res = sections.find(x => x.key === 12);
console.log(res.label);
I would wrap this in a function. Inside function i use the js function find(). If you have more items with the same id then i would use filter instead find.
const sections = [ {key: 0, label: 'Nothing'}, {key: 11, label: 'Alex Right'},{key: 12, label: 'Dolores Black'},{key: 21, label: 'Bobby Smith'},{key: 26, label: 'Andrew Small'} ];
const id = 11;
function getLabel(id) {
return sections.find(e => e.key === id)['label'];
}
console.log(getLabel(id))
The concept is simple, I have two datasets. One is "classes" and one is "attendees". Each Class has a unique ID and some other stuff, like so (the actual data sets are much bigger):
[{class_id: 9, class_cap: 50, class_name: 'Science'},{class_id: 10, class_cap: 30, class_name: 'French'}]
Attendees is similar, where class_id represents the class they are attending:
[{attendee_id: 55, class_id: 9, attendee_name: 'Jack'},{attendee_id: 56, class_id: 10, attendee_name: 'Jill'}]
What I need to do is be able to find out the quantity of students that will be attending each class. I have tried to do it using a for loop and if statement, in an attempt to create a new array for every class which stores the attendee ID of every student attending it (then I can just use length to get quantity of students), but it's not working properly and I can't wrap my head around the correct implementation. The idea is to iterate through every class, and then for every class, iterate through all the attendees to find ones with the same class_id, and then add it to the attendeeArray.
for (let i = 0; i < classes.length; i++){
let classID = classes[i].class_id;
let attendeeArray = [];
for (let d = 0; d < attendees.length; d++){
if(attendees[i].class_id == classID){
attendeeArray[i] = attendees[i].attendee_id;
}
console.log(`Attendance number for class ID ${classID} is ${attendeeArray.length}`)
}
Is there a better way to do this? Any method is fine. Thanks
Try this:
const classes = [{class_id: 9, class_cap: 50, class_name: 'Science'},{class_id: 10, class_cap: 30, class_name: 'French'}]
const students = [{attendee_id: 55, class_id: 9, attendee_name: 'Jack'},{attendee_id: 56, class_id: 10, attendee_name: 'Jill'}]
const classOccupancy = classes.map(oneClass => ({
class_id:oneClass.class_id,
number_attendees: students.filter(student => student.class_id === oneClass.class_id).length
}))
console.log(
`Attendance number for class ID ${classOccupancy[0].class_id} is ${classOccupancy[0].number_attendees}`
)
A bit to late:
let classes = [{ class_id: 9, class_cap: 50, class_name: 'Science' }, { class_id: 10, class_cap: 30, class_name: 'French' }];
let attendees = [{ attendee_id: 55, class_id: 9, attendee_name: 'Jack' }, { attendee_id: 56, class_id: 10, attendee_name: 'Jill' }];
let attClassesCount = classes.map(c => {
let attCount = attendees.filter(a => a.class_id === c.class_id).length;
return { class_id: c.class_id, attendees_count: attCount }
})
console.log(attClassesCount);
I have an JSON-Object as follows:
Input for the months is
customerSend,customerReceived,totalSendAllCustomers,totalReceivedAllCustomers
var emailObj = {
"kundenNummer":17889,
"jahre":
{
2017:{
"Januar":[15,30,75,125],
"Februar":[17,32,77,127],
"März":[19,34,79,129],
},
2018:{
"Januar":[28,12,66,198],
"Oktober":[40,4,40,5],
}
}
}
How exactly do I access the specific year?
I already tried it like this:
var keysYears = Object.keys(emailObj.jahre);
var currentSelectedYear = keysYears[0];
var keysMonth = Object.keys(emailObj.jahre[currentSelectedYear]);
var currentSelectedMonth = keysMonth[0];
document.write(emailObj.jahre[currentSelectedYear].2017[0]);
I also tried some other ways of doing this but I already deleted those.
Can you tell me how to access the 2017 or 2018 data?
I know that I could convert them into strings but I want to know if I could also do it this way.
You can call the properties of your object emailObj by their names.
Either with a dot notation
emailObj.kundenNummer
Or by brackets notation
emailObj["kundenNummer"]
The dot notation won't work in your case because the name of your property is a number. You should then use
emailObj.jahre["2017"]
var emailObj = {
"kundenNummer": 17889,
"jahre": {
"2017": {
"Januar": [15, 30, 75, 125],
"Februar": [17, 32, 77, 127],
"März": [19, 34, 79, 129],
},
"2018": {
"Januar": [28, 12, 66, 198],
"Oktober": [40, 4, 40, 5],
}
}
};
let year = "2017";
let month = "Januar";
console.log(emailObj.jahre[year][month]);
You should use bracket notation.
document.write(emailObj.jahre[currentSelectedYear][currentSelectedMonth][0]);
var emailObj = {
"kundenNummer":17889,
"jahre":
{
2017:{
"Januar":[15,30,75,125],
"Februar":[17,32,77,127],
"März":[19,34,79,129],
},
2018:{
"Januar":[28,12,66,198],
"Oktober":[40,4,40,5],
}
}
}
var keysYears = Object.keys(emailObj.jahre);
var currentSelectedYear = keysYears[0];
var keysMonth = Object.keys(emailObj.jahre[currentSelectedYear]);
var currentSelectedMonth = keysMonth[0];
document.write(emailObj.jahre[currentSelectedYear][currentSelectedMonth][0]);
In a JavaScript object, the key is always a string, even if you use an integer it will be converted into a string.
obj = {
key1: //contents
key2: //contents
}
To access a specific key:
obj.key1
obj['key1']
For your example:
emailObj.jahre['2017']
emailObj['jahre']['2017']
Use the for in looping construct to loop through the keys of an object:
var emailObj = {
"kundenNummer":17889,
"jahre": {
2017:{
"Januar":[15,30,75,125],
"Februar":[17,32,77,127],
"März":[19,34,79,129],
},
2018:{
"Januar":[28,12,66,198],
"Oktober":[40,4,40,5],
}
}
}
for (key in emailObj.jahre) {
console.log(emailObj.jahre[key]) //Here key will be '2017', '2018' etc
}
You cannot access with dot notation properties which contain as name a number in JavaScript. Instead you should consider using bracket notation.
Example:
emailObj.jahre['2017']
var emailObj = {
"kundenNummer": 17889,
"jahre": {
2017: {
"Januar": [15, 30, 75, 125],
"Februar": [17, 32, 77, 127],
"März": [19, 34, 79, 129],
},
2018: {
"Januar": [28, 12, 66, 198],
"Oktober": [40, 4, 40, 5],
}
}
};
console.log(emailObj['jahre']['2017']);
console.log(emailObj.jahre['2017']);
Below is the layout of my JSON File.
{
"questions": ["Question1", "Question2"],
"orgs": ["Org1", "Org2", "Org3"],
"dates": ["Q1", "Q2", "Q3"],
"values": [
[
[5, 88, 18],
[50, 83, 10],
[29, 78, 80]
],
[
[46, 51, 61],
[95, 21, 15],
[49, 86, 43]
]
]
}
I'm trying to retrieve a single array of values by looping through each question, indexed by an "orgs" value and then adding each value retrieved and dividing it by data.dates.length.
Here is my code;
d3.json("data.json", function(error, data) {
var array = new Array()
var orgS = "Org2"
var org = data.orgs.indexOf(orgS);
for (var question = 0; question < data.questions.length; question++) {
array.push(
data.values[question][org]
)
console.log(array)
}
// add array together
array.reduce(function(a, b) {
return a + b;
})
// calculate average
var avg = array / data.dates.length;
})
Here is a plnk;
http://plnkr.co/edit/wMv8GmkD1ynjo9WZVlMb?p=preview
I think the issue here is how I'm retrieving the values in the first place? as at the moment, although I am retrieving the correct values in the console log, I'm getting the array twice, and both times inside nested arrays. I'm not so sure how to remedy the problem?
For reference;
[question1][org1] corresponds to the values [5, 88, 18].
Hope someone can offer some advice here?
Thanks!
Since you clarified your question to indicate you want to calculate separate averages for each question, I've rewritten my answer. You should do all the calculations in the for loop, since the loop is looping through the questions. Then store your averages in an array.
d3.json("data.json", function(error, data) {
var averages = new Array()
var orgS = "Org2"
var org = data.orgs.indexOf(orgS);
var values, sum;
for (var question = 0; question < data.questions.length; question++) {
// get the values for the question/org
values = data.values[question][org];
// calculate the sum
sum = values.reduce(function(a, b) {
return a + b;
});
// calculate the average
averages.push(sum / values.length);
}
console.log(averages);
});
Perform the .reduce() in the for loop and push that result into array. That will give you the an array of the results you expected.
array.push(data.values[question][org].reduce(function(a, b) {
return a + b
}, 0) / data.dates.length)
[
47.666666666666664,
43.666666666666664
]
Currently, you're attempting to perform addition on the arrays themselves in the .reduce() callback instead of reducing the members of each individual array to their sum, and then average.
Demo: (Click the text below to show the whole function)
var data = {
"questions": ["Question1", "Question2"],
"orgs": ["Org1", "Org2", "Org3"],
"dates": ["Q1", "Q2", "Q3"],
"values": [
[
[5, 88, 18],
[50, 83, 10],
[29, 78, 80]
],
[
[46, 51, 61],
[95, 21, 15],
[49, 86, 43]
]
]
}
x(data)
// Your callback function.
function x(data) {
var array = new Array()
var orgS = "Org2"
var org = data.orgs.indexOf(orgS);
for (var question = 0; question < data.questions.length; question++) {
array.push(data.values[question][org].reduce(function(a, b) {
return a + b
}, 0) / data.dates.length)
}
console.log(array)
}
Instead of a for loop, you could also use .map().
var array = data.questions.map(function(_, question) {
return data.values[question][org].reduce(function(a, b) {
return a + b
}, 0) / data.dates.length
})
Demo: (Click the text below to show the whole function)
var data = {
"questions": ["Question1", "Question2"],
"orgs": ["Org1", "Org2", "Org3"],
"dates": ["Q1", "Q2", "Q3"],
"values": [
[
[5, 88, 18],
[50, 83, 10],
[29, 78, 80]
],
[
[46, 51, 61],
[95, 21, 15],
[49, 86, 43]
]
]
}
x(data)
// Your callback function.
function x(data) {
var orgS = "Org2"
var org = data.orgs.indexOf(orgS);
var array = data.questions.map(function(_, question) {
return data.values[question][org].reduce(function(a, b) {
return a + b
}, 0) / data.dates.length
})
console.log(array)
}
You need to store the sum, the result of reduce.
// add array together
// store in sum
var sum = array.reduce(function(a, b) {
return a + b;
}, 0); // use 0 as start value
For the average, you do not need the length of data.dates but from array, because you collecting the values and this length is important.
// calculate average
var avg = sum / array.length;
Together for all values, you might get this
var data = { "questions": ["Question1", "Question2"], "orgs": ["Org1", "Org2", "Org3"], "dates": ["Q1", "Q2", "Q3"], "values": [[[5, 88, 18], [50, 83, 10], [29, 78, 80]], [[46, 51, 61], [95, 21, 15], [49, 86, 43]]] },
sum = [];
data.values.forEach(function (a, i) {
sum[i] = sum[i] || [];
a.forEach(function (b) {
b.forEach(function (c, j) {
sum[i][j] = sum[i][j] || 0;
sum[i][j] += c;
});
});
});
data.avg = sum.map(function (a, i) {
return a.map(function (b) {
return b / data.values[i].length;
});
});
console.log(sum);
console.log(data);
I have a json object {"yAxis" : { "Batting" : [10, 20, 30, 40] , "Bowling" : [10, 30, 50, 70], "Fielding" : [20, 40, 50, 70] } },
and want to convert to json array like this
[ { "name": "Batting" ,"data": [10,20,30,40]} , { "name": "Bowling" ,"data": [10,30,50,70] },{ "name": "Fielding" ,"data": [20,40,50,70]}]
I can create json object for each index but how can i put those to json array?
for(var abc in objJSON.yAxis)
{
seriesValues += JSON.stringify({name:abc,data:(objJSON.yAxis)[abc]});
}
Any help?
You can just loop through creating the object, don't worry about stringifying it.
var obj = {"yAxis" : { "Batting" : [10, 20, 30, 40] , "Bowling" : [10, 30, 50, 70], "Fielding" : [20, 40, 50, 70] } };
var keys = Object.keys(obj.yAxis),
narray = [];
keys.forEach(function(v) {
narray.push({ "name": v, "data": obj.yAxis[v] });
});
Then, if you need to stringify it, you can simply do a JSON.stringify(narray) later on.
You're close:
var seriesValues = [];
for (var abc in objJSON.yAxis) {
seriesValues.push({name: abc, data: objJSON.yAxis[abc]});
}
That will make a javascript array. If you need it as a JSON string then append:
var myString = JSON.stringify(seriesValues);
Simply stringify after the array generated all around.
var result = [];
for(var name in objJSON.yAxis)
{
result.push({name: name, data: objJSON.yAxis[name]});
}
return JSON.stringify(result);