JQuery JSON [object Object] - javascript

I have a JSON that is structured like so:
students.json (UPDATED FROM COMMENTS BELOW)
{
Cindy: { age: 9, m1: 80, m2: 90, s1: 90, s2: 100 },
Mark: { age: 12, m1: 80, m2: 90, s1: 90, s2: 100 },
Jeff: { age: 8, m1: 90, m2: 90, s1: 90, s2: 95 },
Ann: { age: 11, m1: 90, m2: 60, s1: 90, s2: 100 },
Jason: { age: 5, m1: 95, m2: 30, s1: 90, s2: 185 },
Harvey: { age: 10, m1: 100, m2: 70, s1: 90, s2: 100 },
Mike: { age: 9, m1: 100, m2: 80, s1: 90, s2: 82 },
Ross: { age: 9, m1: 88, m2: 90, s1: 90, s2: 100 },
};
In my javascript code I'm importing multiple JSON using JQuery.
var objects = {};
$.getJSON("object1.json", function (data) {
objects = data;
});
var students = {};
$.getJSON("info.json", function (data) {
students = data;
});
// .......
function function1(object) {}
function function2(object) {}
// .......
function main() {
function1(object1);
function2(object2);
}
When I inspect the imported object students, I get:
[object Object]:{
"Cindy" : {"age": 9, "m1":80, "m2":90, "s1":90 , "s2":100},
"Mark" : {"age": 12, "m1":80, "m2":90, "s1":90 , "s2":100},
"Jeff" : {"age": 8, "m1":90, "m2":90, "s1":90 , "s2":95},
"Ann" : {"age": 11, "m1":90, "m2":60, "s1":90 , "s2":100},
"Jason" : {"age": 5, "m1":95, "m2":30, "s1":90 , "s2":185},
"Harvey" : {"age": 10, "m1":100, "m2":70, "s1":90 , "s2":100},
"Mike" : {"age": 9, "m1":100, "m2":80, "s1":90 , "s2":82},
"Ross" : {"age": 9, "m1":88, "m2":90, "s1":90 , "s2":100}
}
It appears that this [object Object] is now a "key"?
UPDATED:
My original question was from the thought that this was preventing me from accessing the object, but that was not my problem. It operates as expected. I can access students.Cindy.age //9 just fine. My problem is that the getJSON happens AFTER the function call so "undefined" objects are being passed into the functions. I need the html to load first as some of the javascript functions manipulate the html page.

you can access like the following 2 types
students.Cindy.age
students['Cindy']['age']

Fix the issues with missing commas around the array properties and assign the outer object to a variable. Then you can use bracket/dot notation to access the properties. You should also fix the nested objects indentation to make your code easier to read.
Check out this example.
var data = {
"Cindy": {
"age": 9,
"m1": 80,
"m2": 90,
"s1": 90,
"s2": 100
},
"Mark": {
"age": 12,
"m1": 80,
"m2": 90,
"s1": 90,
"s2": 100
}
}
Now the following accesses the data:
alert(data["Cindy"].age);
alert(data["Mark"].m1);

There are multiple issues. $.getJSON("info.json" these are async in nature. Instead of $.getJSON, u can use fetch It has better support. Using fetch requests. Promise.all wait for the responses then you can perform the task.
$(function () {
function function1(objects) {
console.log(objects)
}
function function2(students) {
console.log(students.Cindy.age)
console.log(students.Cindy.m1)
}
/*
var objects = {};
$.getJSON("object1.json", function (data) { // these are async in nature
objects = data;
});
var students = {};
$.getJSON("info.json", function (data) { // these are async in nature
students = data;
});
*/
// instead of $.getJSON, u can use `fetch` It has better support
const promises = [fetch("object1.json").then(res => res.json()) , fetch("info.json").then(res => res.json()]
Promise.all(promises).then((results) => {
const [objects, students] = results// data is avaible here,
function1(objects); // do something with objects
function2(students);// do something with students
})
})();

Related

Re-format an array of objects in Javascript in custom array format by property id

I am having trouble reformatting an Object array in Javascript. I have an array that looks like this:
[
{
"deviceid": 42,
"x": "2022-03-26T00:00:18",
"y": 17.8,
},
{
"deviceid": 42,
"x": "2022-03-26T00:01:18",
"y": 17.8,
},
{
"deviceid": 43,
"x": "2022-03-26T00:02:18",
"y": 17.8,
{
"deviceid": 43,
"x": "2022-03-26T00:02:18",
"y": 17.8,
}]
I want to re-shape it so the new form will be one record per device id and all x and y values in the same row.
[
{
"deviceid": 42,
"x": ["2022-03-26T00:00:18","2022-03-27T00:00:18"],
"y": [17.8, 15.6],
},
{
"deviceid": 43,
"x": ["2022-03-26T00:01:18","2022-03-27T00:00:18"],
"y": [17.8, 19.1],
}]
How can I make this happen?
You can use reduce() to do the reduction of your values using a JavaScript object. After the reduction get the values of the object using Object.values().
const data = [
{
deviceid: 42,
x: "2022-03-26T00:00:18",
y: 17.8,
},
{
deviceid: 42,
x: "2022-03-26T00:01:18",
y: 15.6,
},
{
deviceid: 43,
x: "2022-03-26T00:02:18",
y: 17.8,
},
{
deviceid: 43,
x: "2022-03-26T00:02:18",
y: 19.1,
},
];
const result = data.reduce((devices, device) => {
// check if we have encountered this decive before using the deviceId
if (!devices.hasOwnProperty(device.deviceid)) {
// we have not: create an key-value pair using device ID as key and device info as value
// use an array for x and y
devices[device.deviceid] = {
deviceId: device.deviceid,
x: [device.x],
y: [device.y],
};
} else {
// we have seen this device before
// get the device value using the key (deviceId) and push new x and y values to it
const curDev = devices[device.deviceid];
curDev.x.push(device.x);
curDev.y.push(device.y);
}
// return JS object of devices for next iteration/ result
return devices;
}, {});
console.log(Object.values(result));
Please note: I think the input you have provided in your question contains some errors probably from copy/ pasting as the expected output contains values that are not in the input at all. I have changed values of y in the input to show you that output is actually what you expect.

Extract data from an array of Object

I have this array of Object that I am getting from my database:
[Array of Object][1]
I would like to make an array of array for each value, but I can't manage to find a way to do it as I'm a beginner of javascript.
For example :
var Stats=[
[39,49,43,42,41,35], //SGW Value for each Object
[37,44,49,46,52,42], //UD Value for each Object
[8,11,8,8,16,15], //Virtual Value for each Object
...
]
The goal is to make a chart on chart.js that look like that :
[Chart Goal][2]
I would need to loop the dataset because I'll add more data and it would be way too long to set each dataset individually.
Thanks for your time.
You can do it like this:
let array1 = [
{
param1: 10,
param2: 20
},
{
param1: 30,
param2: 40
}
]
let array2 = array1.map(item => Object.values(item));
console.log(array2); // prints [[10, 20], [30, 40]]
First of all you need to create an array for each property you want to plot; i.e.:
var fsp = [],
msg = [],
sgw = [];
Then you can loop over your dataset and put the data in each array:
yourArray.forEach(function(obj){
//obj takes the value of each object in the database
fsp.push(obj.fsp);
msg.push(obj.msg);
sgw.push(obj.sgw);
})
or, if you are more familiar with for loop
for(var obj of yourArray){
fsp.push(obj.fsp);
msg.push(obj.msg);
sgw.push(obj.sgw);
}
Finally you can create an array as you pointed in your example
var result = [];
result.push(fsp, msg, sgw);
And the result will be
[
[89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
[77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
[24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
]
For more informations take a look at Array.forEach(), Array.push() and for...of documentations
EDIT
As you pointed in your comment, you can generate arrays dynamically creating an object like var arrays = {};. Then in forEach(), or if for...of, you need to loop over objects with a for...in loop. The variable you declare in loop's head takes the value of index, numeric for Arrays, literal for Objects. You have to do something like:
yourArray.forEach(function(obj){
for(let index in obj){
if(!arrays[index]) // check if property has already been set and initialized
arrays[index] = []; // if not, it's initialized
arrays[index].push(obj[index]) // push the value into the array
}
})
Note that Object has been treated as Array because you access its properties with a variable filled at runtime.
The result will be:
arrays = {
fsp: [89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
msg: [77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
sgw: [24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
}
To obtain only arrays use Object.values().
If you cannot imagine how this works, I suggest you to make some examples in Chrome Developer Tools' console, or in Node's console, or wherever you can have a realtime feedback, putting in the middle of code some console.log() of variables

Trouble at comparing arrays

I have 'shared.checkedFacility' scope array in controller which read something like:
[14, 49, 93, 122, 44, 40, 88, 83, 65, 9, 38, 28, 8, 53, 125, 155]
and i am dynamically generating two dimensional array in front end where, for example, single dimentional array from 'shared.facilities[$parent.$index]' read like
{"0":56,"1":13,"2":49,"3":3,"4":11,"5":7,"6":19,"7":4,"8":9,"9":131,"10":21}
Now i am comparing this two array in ng-show argument like
containsAny(shared.checkedFacility,shared.facilities[$index])
Where as function defination is like
function containsAny(source, target) {
console.log("contains called");
var result = source.filter(function(item) {
return target.indexOf(item) > -1
});
return (result.length > 0);
}
But some how this function is not returning true or false, how to make it work?
Please rescue me since i am afresh here in Angular or in Javascript Env straight from PHP.
You can use Object.keys(), .map() to create an array from shared.facilities[$parent.$index]
// `shared.checkedFacility`
var checkedFacility = [14
, 49
, 93
, 122
, 44
, 40
, 88
, 83
, 65
, 9
, 38
, 28
, 8
, 53
, 125
, 155
];
// shared.facilities[$parent.$index]
var facilities = {
"0": 56,
"1": 13,
"2": 49,
"3": 3,
"4": 11,
"5": 7,
"6": 19,
"7": 4,
"8": 9,
"9": 131,
"10": 21
};
// create an array having values contained in `facilities`
var arr = Object.keys(facilities).map(function(prop, index) {
return facilities[prop]
});
console.log(arr)
function containsAny(source, target) {
console.log("contains called");
var result = source.filter(function(item) {
return target.indexOf(item) > -1
});
return (result.length > 0);
}
// pass `arr` as second parameter to `containsAny`
var res = containsAny(checkedFacility, arr);
console.log(res)
Your function is failing on:
target.indexOf(item)
because target in your example is an Object and not an Array, so you can't call indexOf function.
So you are most likely getting:
Uncaught TypeError: target.indexOf is not a function
To solve that, you have to pass an Array as target instead of passing an Object.

Code in "Don't Be Scared of Functional Programming"

I've been reading through an article titled Don’t Be Scared Of Functional Programming and there is a piece of code I'm having trouble understanding (pasted below). The code's purpose is to get an item from an array of objects called data. What I don't understand is how the function within the function works. Where is the item argument coming from when you invoke getItem()?
var data = [
{
name: "Jamestown",
population: 2047,
temperatures: [-34, 67, 101, 87]
},
{
name: "Awesome Town",
population: 3568,
temperatures: [-3, 4, 9, 12]
}
{
name: "Funky Town",
population: 1000000,
temperatures: [75, 75, 75, 75, 75]
}
];
function getItem(propertyName) {
// Return a function that retrieves that item, but don't execute the function.
// We'll leave that up to the method that is taking action on items in our
// array.
return function(item) {
return item[propertyName];
}
}
I Understand that JS allows functions to be passed as arguments because they are treated as “first-class objects" in JS, but I don't understand where that item argument would be coming from.
This is defining a function that will accept a parameter called item which can be used to return the propertyName element from the given item. It is the function that is then passed back to the caller of getItem. It would be used as follows:
var getName = getItem('name');
var result = getName(x);
Where x is a variable containing a property called 'name'
Maybe this helps a bit.
It utilized a partial application of the first parameter propertyName with Function.prototype.bind():
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Small example with your data and function:
function getItem(propertyName, item) {
return item[propertyName];
}
var data = [{ name: "Jamestown", population: 2047, temperatures: [-34, 67, 101, 87] }, { name: "Awesome Town", population: 3568, temperatures: [-3, 4, 9, 12] }, { name: "Funky Town", population: 1000000, temperatures: [75, 75, 75, 75, 75] }],
// this returns a function with only item as parameter
getName = getItem.bind(null, 'name');
document.write('<pre>' + JSON.stringify(data.map(getName), 0, 4) + '</pre>');

Add dynamic json to static json

I'm having difficulty creating some code that dynamically creates graphs:
The following code snippet helps create the graph:
xGrid: false,
legend: true,
title: 'Meetings and Hours Used',
points: [
[7, 26, 33, 74, 12, 49, 33, 33, 74, 12, 49, 33],
[32, 46, 75, 38, 62, 20, 52, 75, 38, 62, 20, 52]
],
And I've replaced the points section with this:
points: <%= getJson() %>
And my code behind has function:
public string getJson()
{
var publicationTable = new List<object>{
new { points = "[1,2,3,4,5,6,7,8]," }
};
return (new JavaScriptSerializer()).Serialize(publicationTable);
}
The javascript doesn't seem to be parsing - can anyone please help me :)
Try this.
public string getJson() {
var publicationTable = new[] {
new[] { 1, 2, 3, 4, 5 },
new[] { 6, 7, 8, 9, 10 }
};
return (new JavaScriptSerializer()).Serialize(publicationTable);
}
List<List<int>> lstMainArr = new List<List<int>>();
lstMainArr.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.ToList<int>());
lstMainArr.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.ToList<int>());
Console.Write((new JavaScriptSerializer()).Serialize(lstMainArr));
points: <%= getJson() %>
This outputs whatever the return result type is, so for example:
points: 8 // getJson() returns int
points: test // getJson() returns a string
if you had done:
points = "[1,2,3,4,5,6,7,8],";
return points:
the result would be:
points = [1,2,3,4,5,6,7,8],
However you have:
var publicationTable = new List<object> {
new { points = "[1,2,3,4,5,6,7,8]," }
};
return (new JavaScriptSerializer()).Serialize(publicationTable);
So to determine the output, step through each outer to inner method/object.
Step 1: Serialization - Creates an empty string.
""
Step 2: Serialize List<Object> (basically a JavaScript array)
"[]"
Step 3: Serialize first anonymous Object:
"[{}]"
Step 4: Serialize first property :
"[{"points" : "[1,2,3,4,5,6,7,8],", }]"
No more properties, no more objects, serialization finished. This is not the JSON you were looking for.

Categories