Iterating json array in javascript - javascript

after looking through a lot of similar questions on SO, I still can't iterate my json structure. How can I reach the value (key) of my inner array?
var data = {"User1":{"Service1":2,"Service2":1},"User2":{"Service3":1}}
for(var user in data) {
document.write(user + ': ')
for(var service in data[user]){
document.write(service + ': ' + user[service])
}
document.write("<br />")
}
This prints:
User1: Service1: undefined Service2: undefined
User2: Service3: undefined
And I'd like it to print
User1: Service1: 2 Service2: 1
User2: Service3: 1
Is javascript enough or do I need jQuery?
Thanks in advance!

var data = {
User1: {
Service1: 2,
Service2: 1
},
User2: {
Service3: 1
}
};
for (var user in data) {
console.log("User: " + user);
for (var service in data[user]) {
console.log("\tService: " + service + "; value: " + data[user][service]);
}
}
Replace console.log with document.write or whatever.

document.write(service + ': ' + data[user][service])

Related

Access to Json element with ' ' name (Subquery mysql nodejs)

I'm working in a backend with NodeJS and Mysql, everything is good but recently I've faced a small details where I'm stuck since added a SUBQUERY.
This is the Mysql Query:
var GetHistoryPayments = function(code){
var query = "SELECT DISTINCT students.student_code, " +
"acc.id, " +
"acc.StudentCode, " +
"acc.DocumentDate1, " +
"acc.DocEntry, " +
"acc.DocumentNumber1, " +
"acc.DocTotal1, " +
"acc.GrosProfit, " +
"acc.SumApplied, " +
"acc.DocumentDate2, " +
"acc.DocumentNumber2, " +
"acc.DiffDocTotalPaidToDate as total_pay, " +
"acc.LicTradNum, " +
"acc.created_at, " +
"acc.updated_at, " +
"(SELECT COUNT(*) FROM sap_accounting_state aa WHERE aa.DocumentNumber1 = acc.DocumentNumber1 and aa.tipo like 'Nota%' and aa.SumApplied > 0 ) as credit_notes " +
"FROM sap_accounting_state_students students INNER JOIN sap_accounting_state acc ON students.student_code = acc.StudentCode " +
"WHERE acc.DiffDocTotalPaidToDate = 0 " +
"and acc.Orden = 1 " +
"and acc.DocumentDate1 > '2018-06-01' " +
"and acc.StudentCode = '" + code + "' " +
"GROUP BY acc.DocumentNumber1 " +
"ORDER BY acc.DocumentDate1 desc";
return query;
}
The Object array returned is ok, but the SUBQUERY Object is really weird, it returns with a empty name ('': { credit_notes: 0 }). I suppose the SUBQUERY creates a new object with a known name. ¿How could access a '' json element?, how could put a name SUBQuery like: 'sub': { credit_notes: 0 }?.
Thanks.
[ RowDataPacket {
students: { student_code: '18018' },
acc:
{ id: 3836,
StudentCode: '18018',
DocumentDate1: 2019-01-01T05:00:00.000Z,
DocEntry: 74998,
DocumentNumber1: 10042438,
DocTotal1: 1839017,
GrosProfit: 1839017,
SumApplied: 0,
DocumentDate2: null,
DocumentNumber2: 0,
total_pay: 0,
LicTradNum: '79593354',
created_at: 2019-01-18T19:48:23.000Z,
updated_at: 2019-01-18T19:48:23.000Z },
'': { credit_notes: 0 } },
RowDataPacket {
students: { student_code: '18018' },
acc:
{ id: 3842,
StudentCode: '18018',
DocumentDate1: 2018-12-06T05:00:00.000Z,
DocEntry: 72048,
DocumentNumber1: 10039576,
DocTotal1: 346500,
GrosProfit: 346500,
SumApplied: 0,
DocumentDate2: null,
DocumentNumber2: 0,
total_pay: 0,
LicTradNum: '79593354',
created_at: 2019-01-18T19:48:23.000Z,
updated_at: 2019-01-18T19:48:23.000Z },
'': { credit_notes: 1 } } ... ]
Just take brackets as property accessor.
var item = { '': 'foo' };
console.log(item['']);

Steam trade-offer-manager get items info shorten

I'm trying to build a new project.
It's going to be a tradebot for a website, now to store my received items into my database i whould like some info send with each item (being the name , asseid , tradeid,...).
The following code works.
offers.on('receivedOfferChanged', function (offer, oldState) {
logger.info(offer.partner.getSteam3RenderedID() + " Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));
// Alert us when we accept an offer
if (offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
offer.getReceivedItems(function (err, items) {
if (err) {
logger.error("Couldn't get received items: " + err);
} else {
var names = items.map(function(item) {
return item.name;
});
var assetids = items.map(function(item) {
return item.assetid;
});
// Log a comma-separated list of items received
logger.info("Received: " + names + " " + assetids.join(', '));
}
});
}
});`
But the thing is, is there any way to shorten the following code :
var names = items.map(function(item) {
return item.name;
});
var assetids = items.map(function(item) {
return item.assetid;
});
So it gets the item name , assetid, ... out of the array and stores them in sperate variables ?
You can use push() method to add values into both arrays in a single loop. Try:
var names = [],
assetids = [];
items.forEach(function(item) {
assetids.push(item.assetid);
names.push(item.name);
});

JavaScript foreach Key Value array

I have just this array :
var sArray = {856:"users", 857:"avatars", 858:"emails"};
and I want to use forEach in a way to get key and value from that:
key = 856
value = user
My $.each code doesn't return the result I'm expecting, and I get instead:
856:user
I must be separate that with : to get key and value from this array.
My code is:
$.each(template_array, function(key, value) {
console.log("key: " + "value: " + value);
});
How to access key and value without separate?
Just take Object.keys for the keys and Array.prototype.forEach for the values in plain Javascript.
var sArray = { 856: 'users', 857: 'avatars', 858: 'emails'};
Object.keys(sArray).forEach(function (key) {
document.write('key: ' + key + ', value: ' + sArray[key] + '<br>');
});
Just concatenate them using +
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
$.each(template_array, function(key, value) {
console.log('key:' + key + ', value:' + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
UPDATE :
I think you have an array then use the following code
var template_array = ['856: users',
'857: avatars',
'858: emails'
];
template_array.forEach(function(v) {
v = v.split(':');
console.log('key:' + v[0] + ', value:' + v[1]);
});
try this one
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
var date = [];
$.each(template_array,function (key , val){
date.push({key:key, value:val})
});
console.log(date)
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
for (key in template_array) {
console.log('key:' + key + ', value:' + template_array[key]);
});

Reducing objects properties to get new object

What I have,
var oldUsers = [{
"SID": "S-12",
"Username": "bring.on",
"firstname": "bring",
"lastname": "on",
"email": "emasdklhsjas#gmnailasd.com"
// and so on... 10 more properties
}, {
"SID": "S-13",
"Username": "bring.on1",
"firstname": "bring",
"lastname": "on1",
"email": "sdf#gmnailasd.com"
// and so on... 10 more properties
},
// n numbers of more users...];
What I want,
var newUsers = [{ FullName : "bring on - emasdklhsjas#gmnailasd.com",
value : S-12
},
{ FullName : "bring on1 - sdf#gmnailasd.com",
value : S-13
}, // more users with same properties as abvove
];
What I tried but failed,
var newUsers = $.each(oldUser, function () {
return u = {
value : this.SID,
FullName : this.firstname + " " + this.lastname + " - " + this.email,
};
});
It needs to work on IE-8+ not sure what I am doing wrong really.
All I want is to reduce properties of object in array and get a new object.
Array.prototype.map() can be used to create new array using Plain old Vanilla JavaScript.
The map() method creates a new array with the results of calling a provided function on every element in this array
var newUsers = oldUser.map(function(obj){
return {
value : obj.SID,
FullName : obj.firstname + " " + obj.lastname + " - " + obj.email,
}
});
Note: It will work with IE9+
Using jQuery.map()
var newUsers = jQuery.map(oldUser, function(obj){
return {
value : obj.SID,
FullName : obj.firstname + " " + obj.lastname + " - " + obj.email,
}
});
Your problem is that the .each function doesn't return anything.
http://api.jquery.com/jquery.each/. It iterates over the collection of objects and performs and action on each one. This is different than the functional concept of the higher order function map, which is used to translate one collection into another. (JQuery has a map function too.)
To fix your problem you either need to do:
var newArray = []
var newUsers = $.each(oldUser, function () {
newArray.push ({
value : this.SID,
FullName : this.firstname + " " + this.lastname + " - " + this.email,
});
});
or
var newArray = $.map(oldUsers, function (u,i) {
return {
value : this.SID,
FullName : u.firstname + " " + u.lastname + " - " + u.email,
};
});
Personally, I would go with the second one, as it reduces the number of side effects in your code.
Edit: Apparently, map does not work in IE 8, so the top one is the more correct approach.
Try the following:
var newUsers = [];
$.each(oldUser, function () {
newUsers.push({
value : this.SID,
FullName : this.firstname + " " + this.lastname + " - " + this.email,
});
});
Here is a fiddle for it. Check your console log for the outcome when you run the fiddle.
try this!
var newArr= [];
$.each(users, function (index , user) {
newArr.push({
value : user.SID,
FullName : user.firstname + " " + user.lastname + " - " + user.email,
});
});
Your object is an array of objects, so make use of Array map method:var result = oldUsers.map(function(e){
return { Fullname : e.firstname + e.lastname, value : e['SID']};
});

Unable to loop through json object in nodejs [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I am trying to loop though a JSON object in NODEJS.
I am trying to retrieve the value of for example var value = [table][row][0][STATE] or [table][row][1][STATE] or [table][row][2][STATE] but i am getting STATE undefined error ? Is this the correct way of looping through Json object ?
data = JSON.parse(buffer);
for (var obj in data) {
if (data.hasOwnProperty(obj)) {
console.log(obj);
if (obj == "table") {
for (var prop in data[obj]) {
if (data[obj].hasOwnProperty(prop)) {
console.log(prop + ':' + data[obj][prop][0]['STATE']);
console.log(prop + ':' + data[obj][prop][1]['STATE']);
console.log(prop + ':' + data[obj][prop][2]['STATE']);
console.log(prop + ':' + data[obj][prop][0]['COUNT']);
console.log(prop + ':' + data[obj][prop][0]['COUNT']);
console.log(prop + ':' + data[obj][prop][0]['COUNT']);
}
}
}
}
}
JSON FILE
{
"table":[
{
"row":[
{
"STATE":"A"
},
{
"COUNT":"107"
}
]
},
{
"row":[
{
"STATE":"I"
},
{
"COUNT":"92"
}
]
},
{
"row":[
{
"STATE":"R"
},
{
"COUNT":"2"
}
]
}
]
}
Definitely some odd decisions in your looping. But, try this:
var json = {
"table":[
{ "row":[
{"STATE":"A"},
{"COUNT":"107"}
]
},
{ "row":[
{"STATE":"I"},
{"COUNT":"92"}
]
},
{ "row":[
{"STATE":"R"},
{"COUNT":"2"}
]
}
]
};
var table = json.table;
for( var row in table ) {
for( var field in table[row] ) {
console.log( 'State: ' + table[row][field][0].STATE);
console.log( 'Count: ' + table[row][field][1].COUNT);
}
}
Working jsfiddle: http://jsfiddle.net/pamsvofz/
Update: I'd like to add there really isn't a reason to have the additional row key in the JSON. It really just makes the nesting a little more complicated.

Categories

Resources