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
Related
I have first data object which has a list of cafe, and second data object which has a list of cafe types.
I need find, get and display the corresponding type value from first data object and ID value from second data object.
For example: in list of cafe, I have Pinta with "type" : "3", it means that 3 is Bar from second object.
First object:
{
"list": {
"item": [
{
"ID": "31",
"name": "Staut",
"type": "1",
},
{
"ID": "34",
"name": "Pinta",
"type": "3",
}
]
}
}
And second object:
{
"list": {
"item": [
{
"ID": "1",
"name": "Restaurant",
},
{
"ID": "2",
"name": "Cafe",
},
{
"ID": "3",
"name": "Bar",
}
]
}
}
I can do it with Lodash. It is right, but I can't display it and it uses high memory.
getValues: function() {
_.forEach(CafeJSON.list.item, function(cafeValue) {
_.forEach(TypeJSON.list.item, function(typeValue){
if (cafeValue.type == typeValue.ID) {
console.log("Cafe name is: ", cafeValue.name, "and type is: ", typeValue.name)
}
})
})
}
Result:
I'd simplify the types object down to a object having key value pairs in the form of '3': 'Bar', then loop the items once, overriding the type property's value.
let list = {
"list": {
"item": [{
"ID": "31",
"name": "Staut",
"type": "1",
},
{
"ID": "34",
"name": "Pinta",
"type": "3",
}
]
}
}
let types = {
"list": {
"item": [{
"ID": "1",
"name": "Restaurant",
},
{
"ID": "2",
"name": "Cafe",
},
{
"ID": "3",
"name": "Bar",
}
]
}
}
let typesSimplified = types.list.item.reduce((a, b) => {
a[b.ID] = b.name;
return a;
}, {});
list.list.item.forEach(e => {
e.type = typesSimplified[e.type];
});
console.log(list);
I have an array of object, and i want to convert it into a map of key value pairs with the id as the key. However, I want to do it for both the root level and within the recipes attribute.
Array resp:
[
{
"id": "1",
"recipes": [
{
"id": 4036
},
{
"id": 4041
}
]
},
{
"id": "2",
"recipes": [
{
"id": 4052
},
{
"id": 4053
}
]
}
]
I came across _.keyBy() which maps an attribute as the key, but it doesn't allow nested levels.
Function:
var respObj = _.keyBy(resp, 'id');
Is there an elegant solution to massage resp to make all the objects nested within the array use id as key?
thanks!
you can do it with _.keyBy and _.mapValues
_.chain(resp)
.keyBy('id')
.mapValues(function(item) {
item.recipes = _.keyBy(item.recipes, 'id');
return item;
})
.value();
This is a generic solution that runs _.keyBy recursively on arrays, and the objects inside them:
function deepKeyBy(arr, key) {
return _(arr)
.map(function(o) { // map each object in the array
return _.mapValues(o, function(v) { // map the properties of the object
return _.isArray(v) ? deepKeyBy(v, key) : v; // if the property value is an array, run deepKeyBy() on it
});
})
.keyBy(key); // index the object by the key
}
I've added another level of data in the example (ingredients):
function deepKeyBy(arr, key) {
return _(arr)
.map(function(o) {
return _.mapValues(o, function(v) {
return _.isArray(v) ? deepKeyBy(v, key) : v;
});
})
.keyBy(key);
}
var arr = [{
"id": "1",
"recipes": [{
"id": 4036,
"ingerdients": [{
"id": 5555555
}, {
"id": 5555556
}, {
"id": 5555557
}]
}, {
"id": 4041
}]
}, {
"id": "2",
"recipes": [{
"id": 4052
}, {
"id": 4053
}]
}];
var result = deepKeyBy(arr, 'id');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
You could get a flattened collection of recipes, concatenate the response and then key by id:
var result = _.chain(resp)
.flatMap('recipes')
.concat(resp)
.keyBy('id')
.value()
The flatMap call will pluck all the recipes from the response and flatten the arrays so we're left with this:
[
{ "id": 4036 },
{ "id": 4041 },
{ "id": 4052 },
{ "id": 4053 }
]
The response is then appended to this array using concat so we then have:
[
{ "id": 4036 },
{ "id": 4041 },
{ "id": 4052 },
{ "id": 4053 },
{ "id": "1", recipes: ... },
{ "id": "2", recipes: ... }
]
Finally we use keyBy to get the required structure .
var resp = [
{
"id": "1",
"recipes": [
{
"id": 4036
},
{
"id": 4041
}
]
},
{
"id": "2",
"recipes": [
{
"id": 4052
},
{
"id": 4053
}
]
}
]
var result = _.chain(resp)
.flatMap('recipes')
.concat(resp)
.keyBy('id')
.value()
document.getElementById('result').textContent = JSON.stringify(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
<p>
<pre id="result"></pre>
</p>
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>');
main.php jQuery code:
$.getJSON('posts.php',function(data){
data.posts.forEach(function(post){
// set variables and append divs to document
})
data.comments.forEach(function(post){
// set variables and append divs to document
})
})
(Old - Works with current jQuery code)
Example object containing 2 posts and 3 comments. Post with id: 5 has 1 comment and post id: 2 has 2 comments.
// the two posts ID: 5 and 2
{"posts":[{
"id":"5",
"image":"link.jpg",
"submitter":"4322309",
"views":"3"
},
{
"id":"2",
"image":"link.jpg",
"submitter":"4322309",
"views":"10"
}],
// now each comment tied to the posts
"comments":[
{
"id":"1",
"submitter":"submitter",
"time":"2435657",
"comment":"comment",
"score":"10",
"postid":"2"
},
{
"id":"2",
"submitter":"submitter",
"time":"2435657",
"comment":"comment",
"score":"10",
"postid":"2"
},
{
"id":"3",
"submitter":"submitter",
"time":"2435657",
"comment":"comment",
"score":"10",
"postid":"5"
}]}
(NEW - Does not work with current jQuery code)
Example object containing 2 posts and 3 comments. Post with id: 5 has 1 comment and post id: 2 has 2 comments.
// the two posts ID: 5 and 2
{
"posts":{
"5": {
"id":"5",
"image":"link.jpg",
"submitter":"4322309",
"views":"3"
},
"2": {
"id":"2",
"image":"link.jpg",
"submitter":"4322309",
"views":"5"
}
},
// now each comment tied to the posts
"comments":{
"2": [{
"id":"1",
"submitter":"submitter",
"time":"2435657",
"comment":"comment",
"score":"10",
"postid":"2"
},
{
"id":"2",
"submitter":"submitter",
"time":"2435657",
"comment":"comment",
"score":"10",
"postid":"2"
}
],
"5": [{
"id":"3",
"submitter":"submitter",
"time":"2435657",
"comment":"comment",
"score":"10",
"postid":"5"
}]
}
}
I'm not sure how to use this JSON object in this new scenario.
Basically how do I loop through this new one?
You can easily iterate like this:-
$.each(data['posts'], function(outerKey, idVal) { //outerKyeas are 2, 5
$.each(idVal, function(innerKey, val) { // innerKeys are id,submitter etc
console.log(innerKey, val);
});
});
Comments can be looped through like the same way.
First option (vanilla JS):
var postObj;
for (var id in data.posts) {
postObj = data.posts[id];
// do your thing
}
var commentList;
for (var id in data.comments) {
commentList = data.comments[id];
commentList.forEach(function(comment) {
// do your thing
});
}
For more info on for...in loops https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Second Option (jQuery):
$.each(data.posts, function(id, post) {
// do your thing
});
$.each(data.comments, function(id, commentList) {
$.each(commentList, function(index, comment) {
// do your thing. you could also use the forEach loop if you want
});
});
For more info on $.each http://api.jquery.com/jquery.each/
Well I say you need 3 loops here to fetch each comment object like
DEMO
$(data.comments).each(function(index,commentArray){
$.each(commentArray,function(index,value){
$.each(value,function(index1,value1){
console.log(value1);
});
});
});
for Post you can get it with a single loop
$.each(data.posts,function(index,post){
console.log(post);
});
Try $.each coupled with a basic 'for (var post in data.posts)' loop:
var data = {
"posts": {
"5": {
"id": "5",
"image": "link.jpg",
"submitter": "4322309",
"views": "3"
},
"2": {
"id": "2",
"image": "link.jpg",
"submitter": "4322309",
"views": "5"
}
},
// now each comment tied to the posts
"comments": {
"2": [{
"id": "1",
"submitter": "submitter",
"time": "2435657",
"comment": "comment",
"score": "10",
"postid": "2"
}, {
"id": "2",
"submitter": "submitter",
"time": "2435657",
"comment": "comment",
"score": "10",
"postid": "2"
}],
"5": [{
"id": "3",
"submitter": "submitter",
"time": "2435657",
"comment": "comment",
"score": "10",
"postid": "5"
}]
}
};
for (var post in data.posts) {
$.each(data.comments[data.posts[post].id], function() {
alert("Post: " + data.posts[post].id + ", Comment ID: " + this.id + ', Comment Text: "' + this.comment + '"')
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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...
}
}