I always think it's going to be easy... I plan to use the json below to build router objects. I put a console.log and so I could have a break point spot so I could try to figure out how to access the the object properties from the chrome console. It never goes into the for loop though.
The main question is how to properly turn the JSON into objects and how to access it's properties.
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('JSON/data.json', function(json) {
for (var i=0;i<json.length;i++){
console.log("in for loop");
}
});
});
</script>
{
"_id": {
"$oid": "4f91f2c9e4b0d0a881cf86c4"
},
"DSC21": {
"Router": {
"online": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
],
"bytes": [
"59.5721304971465",
"17014.1911069063",
"14858.8518936735",
"6875.20981475265",
"15157.6891384625",
"6363.47544785913",
"29446.2111270486",
"11517.9296243171",
"27077.9747917112",
"19867.79381695"
]
}
},
"DSC22": {
"Router": {
"online": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
],
"bytes": [
"59.5721304971465",
"17014.1911069063",
"14858.8518936735",
"6875.20981475265",
"15157.6891384625",
"6363.47544785913",
"29446.2111270486",
"11517.9296243171",
"27077.9747917112",
"19867.79381695"
]
}
},
"DSC23": {
"Router": {
"online": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
],
"bytes": [
"59.5721304971465",
"17014.1911069063",
"14858.8518936735",
"6875.20981475265",
"15157.6891384625",
"6363.47544785913",
"29446.2111270486",
"11517.9296243171",
"27077.9747917112",
"19867.79381695"
]
}
},
"DSC24": {
"Router": {
"online": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
],
"bytes": [
"59.5721304971465",
"17014.1911069063",
"14858.8518936735",
"6875.20981475265",
"15157.6891384625",
"6363.47544785913",
"29446.2111270486",
"11517.9296243171",
"27077.9747917112",
"19867.79381695"
]
}
}
}
The variable json is already an object, but it is not an array, so a typical for-loop is insufficient. Since json.length is undefined, i<json.length fails on the first iteration and you skip over the loop.
for (var key in json) {
// key is your DSCxxx
// json[key] is the corresponding object
}
JSON is natively available in JavaScript, you traverse it like you would traverse any object or array.
json["DSC21"]["Router"]["online"][0]; // 1
json.DSC21.Router.online[0]; // equivalent
json.DSC21.Router.online.0; // INCORRECT
If you don't know the names of the properties and want to loop through them use the for .. in construction:
for (var key in json) {
console.log(key); // _id, DSC21, DCS22 etc..
console.log(json[key]); // { "$oid": "" }, { "Router": ".." } etc.
}
This does leave the hasOwnProperty issue, but it shouldn't be a problem if you're just reading JSON data.
maybe you want to know how to iterate your objects?
here would be how to do that:
for( var key in json ){
if( key != '_id'){
var router = json[key].Router;
for( var i = 0; i < router.online.length; i++ ){
console.log(i + ' is online: ', router.online[i]==1?'true':'false');
}
etc...
}
}
Related
I have an object
{
"input":{
"id": "7879",
"inputType": "9876",
"streamName": "870"
},
"transformation":{
"id": "7",
"dependencies": [
"8i"
],
"dropColumns": "hkj",
"processor": "hgf"
},
"output": {
"id": "v",
"saveMode": "uyt",
"dependentIds": [
"h"
],
"outPartition":[
"hg"
]
}
}
Basically every value leaving the key I have to put it in an array. So input, transformation, output values(which are objects) should be placed inside array.
Expected Output:
{
"input": [
{
"id": "7879",
"inputType": "9876",
"streamName": "870"
}
],
"transformation":[
{
"id": "7",
"dependencies": [
"8i"
],
"dropColumns": "hkj",
"processor": "hgf"
}
],
"output":[
{
"id": "v",
"saveMode": "uyt",
"dependentIds": [
"h"
],
"outPartition":[
"hg"
]
}
]
}
I tried iterating using the for in loop but was not able to achieve the expected output how should I place the values(object) inside array
var arr = [];
for(key in obj){
arr.push(Object.assign(obj[key],{name: key}))
}
You mean this (although not sure why you would need this)?
const input = {
"input":{
"id": "7879",
"inputType": "9876",
"streamName": "870"
},
"transformation":{
"id": "7",
"dependencies": [
"8i"
],
"dropColumns": "hkj",
"processor": "hgf"
},
"output": {
"id": "v",
"saveMode": "uyt",
"dependentIds": [
"h"
],
"outPartition":[
"hg"
]
}
}
Object.keys(input).forEach(key => input[key] = [input[key]] )
console.log(input)
According to the output of the object you provided, a simple implementation of looping the elements and creating the keys as arrays can be:
for(key in obj){
obj[key] = [obj[key]];
}
You could rebuild it using the reduce function if you want to do it immutable:
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
More info see: MDN Webdocs - reduce()
const data = {
"input":{
"id": "7879",
"inputType": "9876",
"streamName": "870"
},
"transformation":{
"id": "7",
"dependencies": ["8i"],
"dropColumns": "hkj",
"processor": "hgf"
},
"output": {
"id": "v",
"saveMode": "uyt",
"dependentIds": ["h"],
"outPartition":["hg"]
}
};
const customFormat = (data) => Object.keys(data).reduce((object, key) => {
object[key] = [data[key]];
return object
}, {});
console.log(customFormat(data));
I've tried searching on here, but I can't figure this out.
I'm trying to do an each function that grabs each title of the object, my json is.
{"games":{
"featured": [
{
"game_id": "2"
},
{
"game_id": "15",
}
],
"popular": [
{
"game_id": "2"
}
],
"new": [
{
"game_id": "2",
},
{
"game_id": "15",
},
{
"game_id": "1",
}
]
}}
My JS is:
$.getJSON("apilink",
function(data) {
$.each(data.games, function(i,category){
alert(category[0]);
});
});
I'm obviously trying to rotate through featured, popular and new. What am I doing wrong? Thanks!
You can use nested $.each() calls to iterate each array of objects at category : property name of "games" property of data
var data = {
"games": {
"featured": [{
"game_id": "2"
}, {
"game_id": "15",
}],
"popular": [{
"game_id": "2"
}],
"new": [{
"game_id": "2",
}, {
"game_id": "15",
}, {
"game_id": "1",
}]
}
};
$.each(data.games, function(i, category) {
console.log(i + ":");
$.each(category, function(key, obj) {
console.log(obj)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
I suppose you want to get featured, popular, new? You already have your answer, The first argument i returns the key of the object, where the second argument returns the value which is category.
$.each(data.games, function(i, category) {
// category is what you are looking for
alert(JSON.stringify(category));
//or
alert(JSON.stringify(data.games[i]));
});
Hope that helps
I am trying to merge two json array with objects as element. You may refer to this plunkr file for both json. I have succesfully retrieve the expected final outcome array id, but I do not know how to form back the expected json as below. I am using underscore js for this purpose.
Note: If object exist in newJson and not in currentJson, after merge, it will be inactive state by default.
I am not sure whether I am using the correct approach. This is what I have try:
var newJsonID = _.pluck(newJson, 'id');
var currentJsonID = _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);
Expected Final Outcome:
[
{
"id": "12",
"property1Name": "1"
"status": "inactive"
},
{
"id": "11",
"property1Name": "1"
"status": "inactive"
},
{
"id": "10",
"property1Name": "1"
"status": "inactive"
},
{
"id": "9",
"property1Name": "1"
"status": "active"
}
]
A solution in plain Javascript with two loops and a hash table for lookup.
function update(newArray, currentArray) {
var hash = Object.create(null);
currentArray.forEach(function (a) {
hash[a.id] = a.status;
});
newArray.forEach(function (a) {
a.status = hash[a.id] || 'inactive';
});
}
var newJson = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
currentJson = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
update(newJson, currentJson);
document.write('<pre>' + JSON.stringify(newJson, 0, 4) + '</pre>');
I have a survey system using Angular and Firebase which stores the results of users answers inside of an object specific to each user. This works well for storing data, but I've realized that it may be difficult to pull the data back out due to each object having a unique name.
I'd like to loop over each object and pull the all of the values together. So for all 50 entries find the total of comprehension.icons.damage[1]
How can I construct a loop that goes over objects with unique names like the objects below?
Here is my json structure
"usersanonymous:-JgTyGt6An3WWyLvnnuu" : {
"comprehension" : {
"-JgTzC0r_H58n7y8Al_-" : {
"date" : 1422154060632,
"icons" : [ {
"damage" : [ null, "0", "3", "3" ],
"ocular" : [ null, "2", "3", "1" ],
"physical therapy" : [ null, "0", "4", "4" ],
"skin" : [ null, "4", "0", "1" ]
} ]
}
}
},
"usersanonymous:-JgU-ryIpI-HR7D4VDkp" : {
"comprehension" : {
"-JgU0MwBwisNbjvRFGOT" : {
"date" : 1422154629142,
"icons" : [ {
"damage" : [ null, "0", "3", "4" ],
"ocular" : [ null, "1", "4", "3" ],
"physical therapy" : [ null, "2", "4", "3" ],
"skin" : [ null, "4", "1", "3" ]
} ]
}
}
}
Given your input data, I would create a function to extract just the data you're interested in. I've written this in raw javascript - if you're using jQuery you may have fun using $.map rather than for (x in y).
var data = {
"usersanonymous:-JgTyGt6An3WWyLvnnuu": {
"comprehension": {
"-JgTzC0r_H58n7y8Al_-": {
"date": 1422154060632,
"icons": [{
"damage": [null, "0", "3", "3"],
"ocular": [null, "2", "3", "1"],
"physical therapy": [null, "0", "4", "4"],
"skin": [null, "4", "0", "1"]
}]
}
}
},
"usersanonymous:-JgU-ryIpI-HR7D4VDkp": {
"comprehension": {
"-JgU0MwBwisNbjvRFGOT": {
"date": 1422154629142,
"icons": [{
"damage": [null, "0", "3", "4"],
"ocular": [null, "1", "4", "3"],
"physical therapy": [null, "2", "4", "3"],
"skin": [null, "4", "1", "3"]
}]
}
}
}
};
function extractComprehension(rawData) {
var result = [];
for (var usersanonymous in rawData) {
usersanonymous = rawData[usersanonymous];
if (usersanonymous.comprehension) {
for (var token in usersanonymous.comprehension) {
token = usersanonymous.comprehension[token];
if (token.icons) {
result.push(token.icons[0]);
}
}
}
}
return result;
}
function sumOf(objectList, property, index) {
var result = 0;
for (var o in objectList) {
var numbers = (objectList[o][property] || []);
if (numbers.length >= index) {
result += parseInt(numbers[index], 10);
}
}
return result;
}
Using this mini api you can get the sum of the properties you're interested in:
// Get the data array.
var comprehension = extractComprehension(data);
// Sum some property.
console.log(sumOf(comprehension, 'damage', 3));
I know there is some functional programming in JavaScript and I am wondering if I can create a function like so using some functional methods easier than just writing the code up myself the procedural way (as you can see below, I am also having some SO formatting issue for some reason).
function mapToFormat(var myarray, var colname) {
}
myarray is actually the following json from a server response...
{
"time": "1",
"col1": "2",
"col2": "3",
"col3": "1"
},
{
"time": "2",
"col2": "3"
},
{
"time": "3",
"col1": "3"
},
{
"time": "4",
"col3": "3"
},
{
"time": "5",
"col1": null
}
I would like to call the function on the above json like so
mapToFormat(myarray, 'col1')
and then have it return data like so (in an array format though)
{
"time": "1",
"col1": "2"
},
{
"time": "3",
"col1": "3"
},
{
"time": "5",
"col1": "null
}
I am thinking maybe I just use
var newData = [];
$.each(data, function (index, value) {
if(value[colname] not exist) {
newData.push({
"time": value['time'],
colname : value[colname]
}
});
});
but I am not sure how to tell the difference between "col1" not being there and "col1" : null as I want to pass through any null values that come through as well.
How I can achieve this? And I am wondering if there is a map function or something I should be using that might be better?
Try this (fiddle: http://jsfiddle.net/GNr8N/1/):
function mapToFormat(myArray, col) {
return myArray.map(function(record){
var result = {
time: record.time,
}
if (typeof record[col] !== 'undefined') {
result[col] = record[col]
}
return result;
})
}
The !== operator does not do type casting, so if record[col] exists, it will be added, even if it is null.