Parsing JsonP with Javascript - javascript

I am trying to parse JSON data like this:
var baseUrl = 'https://api.themoviedb.org/3/movie/'
var movieID = '550'
var detailUrl = '&append_to_response=releases,trailers,credits&callback=?'
var apiKey = '?api_key=Removed_For_Privacy'
The above url with the api key include returns this result:
?({
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": "10.2188172784825",
"poster_path": "/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"production_companies": [
{
"name": "20th Century Fox",
"id": 25
},
{
"name": "Fox 2000 Pictures",
"id": 711
},
{
"name": "Regency Enterprises",
"id": 508
}
],
"production_countries": [
{
"iso_3166_1": "DE",
"name": "Germany"
},
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-14",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if you've never been in a fight?",
"title": "Fight Club",
"vote_average": 7.6,
"vote_count": 2787,
"releases": {
"countries": [
{
"iso_3166_1": "US",
"certification": "R",
"release_date": "1999-10-14"
},
{
"iso_3166_1": "DE",
"certification": "18",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "GB",
"certification": "18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "FR",
"certification": "16",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "TR",
"certification": "",
"release_date": "1999-12-10"
},
{
"iso_3166_1": "BR",
"certification": "feibris",
"release_date": "1999-07-12"
},
{
"iso_3166_1": "FI",
"certification": "K-18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "BG",
"certification": "c",
"release_date": "2012-08-28"
},
{
"iso_3166_1": "IT",
"certification": "VM14",
"release_date": "1999-10-29"
}
]
},
"trailers": {
"quicktime": [],
"youtube": [
{
"name": "Trailer 1",
"size": "HD",
"source": "SUXWAEX2jlg",
"type": "Trailer"
}
]
},
"credits": {
"cast": [
{
"id": 819,
"name": "Edward Norton",
"character": "The Narrator",
"order": 0,
"cast_id": 4,
"profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
},
{
"id": 287,
"name": "Brad Pitt",
"character": "Tyler Durden",
"order": 1,
"cast_id": 5,
"profile_path": "/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"
},
{
"id": 1283,
"name": "Helena Bonham Carter",
"character": "Marla Singer",
"order": 2,
"cast_id": 6,
"profile_path": "/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"
},
{
"id": 7470,
"name": "Meat Loaf",
"character": "Robert 'Bob' Paulson",
"order": 3,
"cast_id": 7,
"profile_path": "/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"
},
{
"id": 7499,
"name": "Jared Leto",
"character": "Angel Face",
"order": 4,
"cast_id": 30,
"profile_path": "/msugySeTCyCmlRWtyB6sMixTQYY.jpg"
},
{
"id": 7471,
"name": "Zach Grenier",
"character": "Richard Chesler",
"order": 5,
"cast_id": 31,
"profile_path": "/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"
},
{
"id": 7497,
"name": "Holt McCallany",
"character": "The Mechanic",
"order": 6,
"cast_id": 32,
"profile_path": "/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"
},
{
"id": 7498,
"name": "Eion Bailey",
"character": "Ricky",
"order": 7,
"cast_id": 33,
"profile_path": "/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"
}
],
"crew": [
{
"id": 7469,
"name": "Jim Uhls",
"department": "Writing",
"job": "Author",
"profile_path": null
},
{
"id": 7474,
"name": "Ross Grayson Bell",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 7475,
"name": "Ceán Chaffin",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 1254,
"name": "Art Linson",
"department": "Production",
"job": "Producer",
"profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
},
{
"id": 7477,
"name": "John King",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7478,
"name": "Michael Simpson",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7479,
"name": "Jeff Cronenweth",
"department": "Camera",
"job": "Director of Photography",
"profile_path": null
},
{
"id": 7480,
"name": "James Haygood",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 7481,
"name": "Laray Mayfield",
"department": "Production",
"job": "Casting",
"profile_path": null
},
{
"id": 1303,
"name": "Alex McDowell",
"department": "Art",
"job": "Production Design",
"profile_path": null
},
{
"id": 7763,
"name": "Ren Klyce",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7764,
"name": "Richard Hymns",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7467,
"name": "David Fincher",
"department": "Directing",
"job": "Director",
"profile_path": "/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"
},
{
"id": 7468,
"name": "Chuck Palahniuk",
"department": "Writing",
"job": "Novel",
"profile_path": "/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"
}
]
}
})
I use this to parse it, however i have no luck
$(document).ready(function() {
$.ajax({
url: baseUrl + movieID +apiKey +detailUrl,
dataType: "jsonp",
success: getGenres,
});
});
function getGenres(data) {
var entries = data
genre = 0,
genre_list = '';
for (genre = 0; genre < entries.genres.name.length; genre++) {
genre_list.push(entries.genres.name[genre]);
}
document.getElementById('Genres').innerHTML = genre_list.join(', ');
Please Help

entries.genres is an Array. It has no .name property. You should be getting an error in your browser's developer console for accessing .length of undefined.
{
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
...
}
So you need to iterate entries.genres, then push the .name of the current genre if that's what you want.
for (genre = 0; genre < entries.genres.length; genre++) {
genre_list.push(entries.genres[genre].name);
}
On a different note, you have two implicit globals.
var entries = data
genre = 0,
genre_list = '';
By forgetting the comma after var entries = data, the next two lines will implicitly create global variables since they're not part of the var statement.
That's why I always use leading commas for variable declarations. Makes it obvious when a comma is missing.
var entries = data
, genre = 0
, genre_list = '';

test.php
<?php
echo 'getGenres({
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": "10.2188172784825",
"poster_path": "/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"production_companies": [
{
"name": "20th Century Fox",
"id": 25
},
{
"name": "Fox 2000 Pictures",
"id": 711
},
{
"name": "Regency Enterprises",
"id": 508
}
],
"production_countries": [
{
"iso_3166_1": "DE",
"name": "Germany"
},
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-14",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if youve never been in a fight?",
"title": "Fight Club",
"vote_average": 7.6,
"vote_count": 2787,
"releases": {
"countries": [
{
"iso_3166_1": "US",
"certification": "R",
"release_date": "1999-10-14"
},
{
"iso_3166_1": "DE",
"certification": "18",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "GB",
"certification": "18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "FR",
"certification": "16",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "TR",
"certification": "",
"release_date": "1999-12-10"
},
{
"iso_3166_1": "BR",
"certification": "feibris",
"release_date": "1999-07-12"
},
{
"iso_3166_1": "FI",
"certification": "K-18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "BG",
"certification": "c",
"release_date": "2012-08-28"
},
{
"iso_3166_1": "IT",
"certification": "VM14",
"release_date": "1999-10-29"
}
]
},
"trailers": {
"quicktime": [],
"youtube": [
{
"name": "Trailer 1",
"size": "HD",
"source": "SUXWAEX2jlg",
"type": "Trailer"
}
]
},
"credits": {
"cast": [
{
"id": 819,
"name": "Edward Norton",
"character": "The Narrator",
"order": 0,
"cast_id": 4,
"profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
},
{
"id": 287,
"name": "Brad Pitt",
"character": "Tyler Durden",
"order": 1,
"cast_id": 5,
"profile_path": "/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"
},
{
"id": 1283,
"name": "Helena Bonham Carter",
"character": "Marla Singer",
"order": 2,
"cast_id": 6,
"profile_path": "/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"
},
{
"id": 7470,
"name": "Meat Loaf",
"character": "Robert Bob Paulson",
"order": 3,
"cast_id": 7,
"profile_path": "/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"
},
{
"id": 7499,
"name": "Jared Leto",
"character": "Angel Face",
"order": 4,
"cast_id": 30,
"profile_path": "/msugySeTCyCmlRWtyB6sMixTQYY.jpg"
},
{
"id": 7471,
"name": "Zach Grenier",
"character": "Richard Chesler",
"order": 5,
"cast_id": 31,
"profile_path": "/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"
},
{
"id": 7497,
"name": "Holt McCallany",
"character": "The Mechanic",
"order": 6,
"cast_id": 32,
"profile_path": "/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"
},
{
"id": 7498,
"name": "Eion Bailey",
"character": "Ricky",
"order": 7,
"cast_id": 33,
"profile_path": "/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"
}
],
"crew": [
{
"id": 7469,
"name": "Jim Uhls",
"department": "Writing",
"job": "Author",
"profile_path": null
},
{
"id": 7474,
"name": "Ross Grayson Bell",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 7475,
"name": "Ceán Chaffin",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 1254,
"name": "Art Linson",
"department": "Production",
"job": "Producer",
"profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
},
{
"id": 7477,
"name": "John King",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7478,
"name": "Michael Simpson",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7479,
"name": "Jeff Cronenweth",
"department": "Camera",
"job": "Director of Photography",
"profile_path": null
},
{
"id": 7480,
"name": "James Haygood",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 7481,
"name": "Laray Mayfield",
"department": "Production",
"job": "Casting",
"profile_path": null
},
{
"id": 1303,
"name": "Alex McDowell",
"department": "Art",
"job": "Production Design",
"profile_path": null
},
{
"id": 7763,
"name": "Ren Klyce",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7764,
"name": "Richard Hymns",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7467,
"name": "David Fincher",
"department": "Directing",
"job": "Director",
"profile_path": "/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"
},
{
"id": 7468,
"name": "Chuck Palahniuk",
"department": "Writing",
"job": "Novel",
"profile_path": "/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"
}
]
}
})';
exit;
?>
javascript code:
<script language="javascript">
jq(document).ready(function() {
jq.ajax({
url: 'test.php',
dataType: "jsonp",
}); });
function getGenres(data){
alert(data.genres.length);
}
</script>
Your json response contains single quotes (') example 'bob' and you've which are not standard, so replace then by \' and then parse your json response.
For reference check jQuery single quote in JSON response
Remove ?( and ) from the starting and end of json response and also remove ' from them and check
var obj = jQuery.parseJSON( '{"adult":false,"backdrop_path":"/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg","belongs_to_collection":null,"budget":63000000,"genres":[{"id":28,"name":"Action"},{"id":18,"name":"Drama"},{"id":53,"name":"Thriller"}],"homepage":"","id":550,"imdb_id":"tt0137523","original_title":"Fight Club","overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground fight clubs forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.","popularity":"10.2188172784825","poster_path":"/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg","production_companies":[{"name":"20th Century Fox","id":25},{"name":"Fox 2000 Pictures","id":711},{"name":"Regency Enterprises","id":508}],"production_countries":[{"iso_3166_1":"DE","name":"Germany"},{"iso_3166_1":"US","name":"United States of America"}],"release_date":"1999-10-14","revenue":100853753,"runtime":139,"spoken_languages":[{"iso_639_1":"en","name":"English"}],"status":"Released","tagline":"How much can you know about yourself if youve never been in a fight?","title":"Fight Club","vote_average":7.6,"vote_count":2787,"releases":{"countries":[{"iso_3166_1":"US","certification":"R","release_date":"1999-10-14"},{"iso_3166_1":"DE","certification":"18","release_date":"1999-11-10"},{"iso_3166_1":"GB","certification":"18","release_date":"1999-11-12"},{"iso_3166_1":"FR","certification":"16","release_date":"1999-11-10"},{"iso_3166_1":"TR","certification":"","release_date":"1999-12-10"},{"iso_3166_1":"BR","certification":"feibris","release_date":"1999-07-12"},{"iso_3166_1":"FI","certification":"K-18","release_date":"1999-11-12"},{"iso_3166_1":"BG","certification":"c","release_date":"2012-08-28"},{"iso_3166_1":"IT","certification":"VM14","release_date":"1999-10-29"}]},"trailers":{"quicktime":[],"youtube":[{"name":"Trailer 1","size":"HD","source":"SUXWAEX2jlg","type":"Trailer"}]},"credits":{"cast":[{"id":819,"name":"Edward Norton","character":"The Narrator","order":0,"cast_id":4,"profile_path":"/iUiePUAQKN4GY6jorH9m23cbVli.jpg"},{"id":287,"name":"Brad Pitt","character":"Tyler Durden","order":1,"cast_id":5,"profile_path":"/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"},{"id":1283,"name":"Helena Bonham Carter","character":"Marla Singer","order":2,"cast_id":6,"profile_path":"/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"},{"id":7470,"name":"Meat Loaf","character":"Robert Bob Paulson","order":3,"cast_id":7,"profile_path":"/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"},{"id":7499,"name":"Jared Leto","character":"Angel Face","order":4,"cast_id":30,"profile_path":"/msugySeTCyCmlRWtyB6sMixTQYY.jpg"},{"id":7471,"name":"Zach Grenier","character":"Richard Chesler","order":5,"cast_id":31,"profile_path":"/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"},{"id":7497,"name":"Holt McCallany","character":"The Mechanic","order":6,"cast_id":32,"profile_path":"/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"},{"id":7498,"name":"Eion Bailey","character":"Ricky","order":7,"cast_id":33,"profile_path":"/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"}],"crew":[{"id":7469,"name":"Jim Uhls","department":"Writing","job":"Author","profile_path":null},{"id":7474,"name":"Ross Grayson Bell","department":"Production","job":"Producer","profile_path":null},{"id":7475,"name":"Ceán Chaffin","department":"Production","job":"Producer","profile_path":null},{"id":1254,"name":"Art Linson","department":"Production","job":"Producer","profile_path":"/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"},{"id":7477,"name":"John King","department":"Sound","job":"Original Music Composer","profile_path":null},{"id":7478,"name":"Michael Simpson","department":"Sound","job":"Original Music Composer","profile_path":null},{"id":7479,"name":"Jeff Cronenweth","department":"Camera","job":"Director of Photography","profile_path":null},{"id":7480,"name":"James Haygood","department":"Editing","job":"Editor","profile_path":null},{"id":7481,"name":"Laray Mayfield","department":"Production","job":"Casting","profile_path":null},{"id":1303,"name":"Alex McDowell","department":"Art","job":"Production Design","profile_path":null},{"id":7763,"name":"Ren Klyce","department":"Sound","job":"Sound Editor","profile_path":null},{"id":7764,"name":"Richard Hymns","department":"Sound","job":"Sound Editor","profile_path":null},{"id":7467,"name":"David Fincher","department":"Directing","job":"Director","profile_path":"/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"},{"id":7468,"name":"Chuck Palahniuk","department":"Writing","job":"Novel","profile_path":"/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"}]}}' );
alert( obj.genres.length );
alert messages showing 3, so your json response is not valid

Related

How to update a field inside the array of object of another array of objects in mongo db? or How to update a field using the array index in mongo db?

This is the structure of my collection of mongodb database. I need to update the status inside each order products. What I need to do?
{
"_id": {
"$oid": "633ab3c11e6e97b6332f56a1"
},
"orders": [
{
"date": "6/10/2022",
"productDetails": {
"0": {
"name": "Top",
"price": "1235",
"quantity": 1,
"status": "placed"
},
"1": {
"name": "Shirt",
"price": "1235",
"quantity": 1,
"status": "placed"
}
},
"billingAddress": {
"address": "My Address",
"city": "City",
"state": "State",
"country": "Country",
"pincode": "123456",
"contact": "1234567890"
},
"paymentMode": "cod"
},
{
"date": "6/10/2022",
"productDetails": {
"0": {
"name": "Top",
"price": "1235",
"quantity": 3,
"status": "placed"
},
"1": {
"name": "Shirt",
"price": "1235",
"quantity": 1,
"status": "placed"
}
},
"billingAddress": {
"address": "My Address",
"city": "City",
"state": "State",
"country": "Country",
"pincode": "123456",
"contact": "1234567890"
},
"paymentMode": "cod"
},
{
"date": "6/10/2022",
"productDetails": {
"0": {
"name": "Shirt",
"price": "234",
"quantity": 1,
"status": "placed"
},
"1": {
"name": "Top",
"price": "123",
"quantity": 1,
"status": "placed"
}
},
"billingAddress": {
"address": "My Address",
"city": "City",
"state": "State",
"country": "Country",
"pincode": "123456",
"contact": "1234567890"
},
"paymentMode": "cod"
}
]
}
I want to update the order product status to shipped, canceled, etc. I have to set status in desired position like the following.
I waant to update the mongodb databse and have to get the result in like the following result.
{
"_id": {
"$oid": "633ab3c11e6e97b6332f56a1"
},
"orders": [
{
"date": "6/10/2022",
"productDetails": {
"0": {
"name": "Top",
"price": "1235",
"quantity": 1,
"status": "caneled"
},
"1": {
"name": "Shirt",
"price": "1235",
"quantity": 1,
"status": "shipped"
}
},
"billingAddress": {
"address": "My Address",
"city": "City",
"state": "State",
"country": "Country",
"pincode": "123456",
"contact": "1234567890"
},
"paymentMode": "cod"
},
{
"date": "6/10/2022",
"productDetails": {
"0": {
"name": "Top",
"price": "1235",
"quantity": 3,
"status": "canceled"
},
"1": {
"name": "Shirt",
"price": "1235",
"quantity": 1,
"status": "shipped"
}
},
"billingAddress": {
"address": "My Address",
"city": "City",
"state": "State",
"country": "Country",
"pincode": "123456",
"contact": "1234567890"
},
"paymentMode": "cod"
},
{
"date": "6/10/2022",
"productDetails": {
"0": {
"name": "Shirt",
"price": "234",
"quantity": 1,
"status": "placed"
},
"1": {
"name": "Top",
"price": "123",
"quantity": 1,
"status": "shipped"
}
},
"billingAddress": {
"address": "My Address",
"city": "City",
"state": "State",
"country": "Country",
"pincode": "123456",
"contact": "1234567890"
},
"paymentMode": "cod"
}
]
}
According to my research, the correct method is as follows:
db.orders.updateOne({_id: ObjectId("633a6a73dd9f8cce0029e53d")},{$set:{"orders.0.productDetails.0.status": "shipped"}})
And the result is :-
{
"_id": {
"$oid": "633ab3c11e6e97b6332f56a1"
},
"orders": [
{
"_id": {
"$oid": "633e8f2d3e3f12f07438cc64"
},
"date": "6/10/2022",
"productDetails": {
"0": {
"name": "Top",
"price": "1235",
"quantity": 1,
"status": "shipped"
},
"1": {
"name": "Shirt",
"price": "1235",
"quantity": 1,
"status": "placed"
}
},
"billingAddress": {
"address": "My Address",
"city": "City",
"state": "State",
"country": "Country",
"pincode": "123456",
"contact": "1234567890"
},
"paymentMode": "cod"
},
{
"_id": {
"$oid": "633e96533e3f12f07438cc65"
},
"date": "6/10/2022",
"productDetails": {
"0": {
"name": "Top",
"price": "1235",
"quantity": 1,
"status": "placed"
},
"1": {
"name": "Shirt",
"price": "1235",
"quantity": 1,
"status": "placed"
},
"2": {
"name": "Jeans",
"price": "1234",
"quantity": 1,
"status": "placed"
}
},
"billingAddress": {
"address": "My Address",
"city": "City",
"state": "State",
"country": "Country",
"pincode": "123456",
"contact": "1234567890"
},
"paymentMode": "cod"
}
]
}

Combine nested data from 2 api

I have 2 api:
Having bank details
Other having user account detail.
User can have more than 1 account with 1 bank. I have to fetch bank name and logo from bank api, and show all the user accounts with name, amount banks name and logo.
Two api data looks like below :
Bank API:
[
{
"id": 2,
"name": "KlikBCA",
"bank_code": "KlikBCA",
"country_code": "ID",
"country_name": "India",
"logo": "url",
"createdAt": null,
"updatedAt": "2021-07-26T14:58:03.000+00:00",
"channels": null
},
{
"id": 7,
"name": "BNI Internet Banking",
"bank_code": "BNI Internet Banking",
"country_code": "ID",
"country_name": "Indis",
"primary_color": "url",
"logo": null,
"createdAt": null,
"updatedAt": "2021-07-26T14:58:03.000+00:00",
"channels": null
}
]
User API:
[
{
"id": "sdf",
"bankId": "7",
"data": [
{
"accountId": “1234”,
"accountHolder": "John Doe",
"accountNumber": "587-2673-989",
"balances": {
"available": 500000,
}
},
{
"accountId": “2345”,
"accountHolder": "John Doe",
"accountNumber": "987-0675-789",
"balances": {
"available": 7500000
}
}
]
},
{
"id": "f230",
"bankId": "3",
"data": [
{
"accountId": "9876",
"accountHolder": "Charls",
"accountNumber": "765-6543-345",
"balances": {
"available": 200000
}
}
]
}
]
i need data to be like this..so that I can use it in my next component, which will take each account with all the bank details.
[
{
"id": "sdf",
"bankId": "7",
"data":
{
"accountId": “1234”,
"accountHolder": "John Doe",
"accountNumber": "587-2673-989",
"balances": {
"available": 500000,
}
},
"bank":{
"id": 7,
"name": "BNI Internet Banking",
"bank_code": "BNI Internet Banking",
"country_code": "ID",
"country_name": "Indis",
"primary_color": "url",
"logo": null,
"createdAt": null,
"updatedAt": "2021-07-26T14:58:03.000+00:00",
"channels": null
}
},
{"id": "sdf",
"bankId": "7",
"data": {
"accountId": “2345”,
"accountHolder": "John Doe",
"accountNumber": "987-0675-789",
"balances": {
"available": 7500000
}
},
"bank":{
"id": 7,
"name": "BNI Internet Banking",
"bank_code": "BNI Internet Banking",
"country_code": "ID",
"country_name": "Indis",
"primary_color": "url",
"logo": null,
"createdAt": null,
"updatedAt": "2021-07-26T14:58:03.000+00:00",
"channels": null
}
},
{
"id": "f230",
"bankId": "3",
"data": {
"accountId": "9876",
"accountHolder": "Charls",
"accountNumber": "765-6543-345",
"balances": {
"available": 200000
},
"bank":{
"name": "Mandiri",
"bank_code": "Mandiri",
"country_code": "ID",
"country_name": "India",
"primary_color": "url",
"logo": null,
"createdAt": null,
"updatedAt": "2021-07-26T14:58:03.000+00:00",
"channels": null
}
}
}
]
You can use loop to merge two api json into one,
this is my code.
hope I can help u.
const banks = [{
"id": 2,
"name": "KlikBCA",
"bank_code": "KlikBCA",
"country_code": "ID",
"country_name": "India",
"logo": "url",
"createdAt": null,
"updatedAt": "2021-07-26T14:58:03.000+00:00",
"channels": null
}, {
"id": 3,
"name": "Mandiri",
"bank_code": "Mandiri",
"country_code": "ID",
"country_name": "India",
"primary_color": "url",
"logo": null,
"createdAt": null,
"updatedAt": "2021-07-26T14:58:03.000+00:00",
"channels": null
}, {
"id": 7,
"name": "BNI Internet Banking",
"bank_code": "BNI Internet Banking",
"country_code": "ID",
"country_name": "Indis",
"primary_color": "url",
"logo": null,
"createdAt": null,
"updatedAt": "2021-07-26T14:58:03.000+00:00",
"channels": null
}]
const users = [{
"id": "sdf",
"bankId": "7",
"data": [{
"accountId": "1234",
"accountHolder": "John Doe",
"accountNumber": "587-2673-989",
"balances": {
"available": 500000,
}
}, {
"accountId": "2345",
"accountHolder": "John Doe",
"accountNumber": "987-0675-789",
"balances": {
"available": 7500000
}
}]
}, {
"id": "f230",
"bankId": "3",
"data": [{
"accountId": "9876",
"accountHolder": "Charls",
"accountNumber": "765-6543-345",
"balances": {
"available": 200000
}
}]
}]
let resultApi = users.map(u => {
const t = banks.find(b => b.id == u.bankId) || {}
return {
...u,
...t
}
})
console.log(resultApi);
first of all, a feedback, you should write json inside code blocks for readability.
your question seems incomplete as what you want to achieve? you want to show these data in UI (html) or create a new json? and how far have you tried?
try to share a codesandbox/codepen link.
remember, you need to loop through both the arrays and first store bank data inside user's account by matching user.bankId === bank.id and then with the new data set you can show it wherever you want. give it a try first and then let us know in comments if you're unable to achieve.

More efficient way to remove from an object attributes present in a group of objects

I'm manipulating some javascript objects and I want to know if is there a more efficient and easy way to process my data.
I already do that, but I'm a beginner in js.
I have four objects with this structure: basically there is an array of blocks and any object has a different number of blocks. In every block, in the features attribute, I have another array with some features.
Then I have another object, and I have to remove from this object (I call it structure) blocks and features that are not present in my four initial object.
This is a sample product object
[
{
"ID": 16293,
"SortNo": "20",
"FeatureGroup": {
"ID": "148",
"Name": {
"Value": "Design",
"Language": "IT"
}
},
"Features": [
{
"Localized": 0,
"ID": "155744521",
"Type": "dropdown",
"Value": "Round",
"CategoryFeatureId": "85327",
"CategoryFeatureGroupID": "16293",
"SortNo": "155",
"PresentationValue": "Rotondo",
"RawValue": "Round",
"LocalValue": [],
"Description": "The external form",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "9397",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Forma",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155655523",
"Type": "multi_dropdown",
"Value": "White",
"CategoryFeatureId": "85298",
"CategoryFeatureGroupID": "16293",
"SortNo": "90",
"PresentationValue": "Bianco",
"RawValue": "White",
"LocalValue": [],
"Description": "The colour of the housing",
"Mandatory": "1",
"Searchable": "1",
"Feature": {
"ID": "10059",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Colore struttura",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155655525",
"Type": "multi_dropdown",
"Value": "White",
"CategoryFeatureId": "85301",
"CategoryFeatureGroupID": "16293",
"SortNo": "80",
"PresentationValue": "Bianco",
"RawValue": "White",
"LocalValue": [],
"Description": "The colour of the band",
"Mandatory": "1",
"Searchable": "1",
"Feature": {
"ID": "11025",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Colore cinturino",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "219617494",
"Type": "y_n",
"Value": "Y",
"CategoryFeatureId": "168947",
"CategoryFeatureGroupID": "16293",
"SortNo": "-6",
"PresentationValue": "Sì",
"RawValue": "Y",
"LocalValue": [],
"Description": "The product is protected from water",
"Mandatory": "0",
"Searchable": "0",
"Feature": {
"ID": "7509",
"Sign": "",
"Measure": {
"ID": "26",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Resistente all'acqua",
"Language": "IT"
}
}
}
]
},
{
"ID": 34567,
"SortNo": "20",
"FeatureGroup": {
"ID": "184",
"Name": {
"Value": "Prestazione",
"Language": "IT"
}
},
"Features": [
{
"Localized": 0,
"ID": "155744528",
"Type": "y_n",
"Value": "N",
"CategoryFeatureId": "94697",
"CategoryFeatureGroupID": "34567",
"SortNo": "800",
"PresentationValue": "No",
"RawValue": "N",
"LocalValue": [],
"Description": "La Frequenza modulare radio produce la miglior recezione di qualsiasi canale radio. Quando viene usato un auricolare, produce un effetto di suono da stereo r",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "2172",
"Sign": "",
"Measure": {
"ID": "26",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Radio FM",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155744530",
"Type": "multi_dropdown",
"Value": "Not supported",
"CategoryFeatureId": "85357",
"CategoryFeatureGroupID": "34567",
"SortNo": "500",
"PresentationValue": "Non supportato",
"RawValue": "Not supported",
"LocalValue": [],
"Description": "Types of memory cards which can be used with this product.",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "730",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Tipi schede di memoria",
"Language": "IT"
}
}
}
]
}
]
Here i loop my initial objects (this.compare_products) to extract, in two arrays (featureGroupIds - featureIds) the ID of my block and the CategoryFeatureId
let featureGroupIds = []
let featureIds = []
this.compare_products.forEach((object) => {
featureGroupIds = featureGroupIds.concat(FeaturesGroups.map(o => o.ID))
featureIds = featureIds.concat(FeaturesGroups.map(o => o.Features.map(o => o. CategoryFeatureId))).flat(2)
})
The two arrays, featureGroupIds and featureIds are now filled with every block ID and every CategoryFeatureId present in my four object.
Now I have to filter the object I call "structure" to remove the block and the features with an ID that is not present in my arrays.
This is my structure, and as you can see is similar.
[
{
"name": "Display",
"data": {
"id": 34566,
"category_id": 2647
},
"features": [
{
"name": "Tipo di display",
"data": {
"id": 85325,
"category_id": 2647,
"feature_id": 9104,
"category_feature_group_id": 34566,
"order": 10100140
}
},
{
"name": "Touch screen",
"data": {
"id": 85331,
"category_id": 2647,
"feature_id": 4963,
"category_feature_group_id": 34566,
"order": 10100129
}
},
{
"name": "Dimensioni schermo",
"data": {
"id": 158002,
"category_id": 2647,
"feature_id": 3544,
"category_feature_group_id": 34566,
"order": 100149
}
},
{
"name": "à di Pixel",
"data": {
"id": 85347,
"category_id": 2647,
"feature_id": 13246,
"category_feature_group_id": 34566,
"order": 100147
}
},
{
"name": "Tipo di vetro",
"data": {
"id": 94704,
"category_id": 2647,
"feature_id": 7610,
"category_feature_group_id": 34566,
"order": 100050
}
}
]
},
{
"name": "Altre caratteristiche",
"data": {
"id": 34569,
"category_id": 2647,
"feature_group_id": 146,
"name": null,
"order": 0
},
"features": [
{
"name": "inside",
"data": {
"id": 110410,
"category_id": 2647,
"feature_id": 18688,
"category_feature_group_id": 34569,
"order": 100000
}
}
]
}
]
Here is my function
structure = structure.filter(featureGroup => this.featureGroupIds.includes(featureGroup.data.id));
structure.map((object) => {
object.features.filter(feature => this.featureIds.includes(feature.data.feature_id))
})
this.featureIds and this.featureGroupIds are the array with the group IDS and with the feature IDS.
Is there a more efficient way to do this?

Parsing JSON Multiple Levels With JavaScript

Hello currently I am trying to get a specific value, but not entirely sure how.
Below is part of the JSON data that i am using. the data is set to equal to "entries"
var entries = "credits": {
"crew": [
{
"id": 7469,
"name": "JimUhls",
"department": "Writing",
"job": "Author",
"profile_path": null
},
{
"id": 7474,
"name": "RossGraysonBell",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 7475,
"name": "CeánChaffin",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 1254,
"name": "ArtLinson",
"department": "Production",
"job": "Producer",
"profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
},
{
"id": 7477,
"name": "JohnKing",
"department": "Sound",
"job": "OriginalMusicComposer",
"profile_path": null
},
{
"id": 7478,
"name": "MichaelSimpson",
"department": "Sound",
"job": "OriginalMusicComposer",
"profile_path": null
},
{
"id": 7479,
"name": "JeffCronenweth",
"department": "Camera",
"job": "DirectorofPhotography",
"profile_path": null
},
{
"id": 7480,
"name": "JamesHaygood",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 7481,
"name": "LarayMayfield",
"department": "Production",
"job": "Casting",
"profile_path": null
},
{
"id": 1303,
"name": "AlexMcDowell",
"department": "Art",
"job": "ProductionDesign",
"profile_path": null
},
{
"id": 7763,
"name": "RenKlyce",
"department": "Sound",
"job": "SoundEditor",
"profile_path": null
},
{
"id": 7764,
"name": "RichardHymns",
"department": "Sound",
"job": "SoundEditor",
"profile_path": null
},
{
"id": 7467,
"name": "DavidFincher",
"department": "Directing",
"job": "Director",
"profile_path": "/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"
},
{
"id": 7468,
"name": "ChuckPalahniuk",
"department": "Writing",
"job": "Novel",
"profile_path": "/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"
}
]
}
}
I then parse through the data using this:
crew_member = 0,
crew_members = [];
for (crew_member = 0; crew_member < entries.credits.crew.length; crew_member++) {
crew_members.push(entries.credits.crew[crew_member].job + ': ' + entries.credits.crew[crew_member].name);
}
document.getElementById('Crew').innerHTML = crew_members.join(',');
Everything works on my end. The problem I am having is how to specifically get for example the director and the director only.
It's a simple if statement:
for (crew_member = 0; crew_member < entries.credits.crew.length; crew_member++) {
if (entries.credits.crew[crew_member].job == "Director") {
crew_members.push(entries.credits.crew[crew_member].job + ': ' + entries.credits.crew[crew_member].name);
}
}
try jquery
jQuery.grep(entries.credits.crew,function(n,i){ return (n.job == "Director") });
This should return you array of crew elements which has job as directors.
Thanks.
Simplest Way
entries.credits.crew.filter(function(a){ return a.job == 'Director'; });
You'll get a separate array of objects where job is "Director"
You can filter the items and still return and array like this:
entries.credits.crew.filter(function(member){ return member.job === "DirectorofPhotography" } );
You can also add this:
entries.credits.crew.filter(function(member){ return member.job === "DirectorofPhotography" } ).map(function(member){
return member.job+ ': ' + member.name;}).join(',');
Update 1
This is based on this Object, since the one provide does not seem to be in the correct format:
var entries = { "credits" : {"crew":[
{
"id": 7469,
"name": "JimUhls",
"department": "Writing",
"job": "Author",
"profile_path": null
},
{
"id": 7474,
"name": "RossGraysonBell",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 7475,
"name": "CeánChaffin",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 1254,
"name": "ArtLinson",
"department": "Production",
"job": "Producer",
"profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
},
{
"id": 7477,
"name": "JohnKing",
"department": "Sound",
"job": "OriginalMusicComposer",
"profile_path": null
},
{
"id": 7478,
"name": "MichaelSimpson",
"department": "Sound",
"job": "OriginalMusicComposer",
"profile_path": null
},
{
"id": 7479,
"name": "JeffCronenweth",
"department": "Camera",
"job": "DirectorofPhotography",
"profile_path": null
},
{
"id": 7480,
"name": "JamesHaygood",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 7481,
"name": "LarayMayfield",
"department": "Production",
"job": "Casting",
"profile_path": null
},
{
"id": 1303,
"name": "AlexMcDowell",
"department": "Art",
"job": "ProductionDesign",
"profile_path": null
},
{
"id": 7763,
"name": "RenKlyce",
"department": "Sound",
"job": "SoundEditor",
"profile_path": null
},
{
"id": 7764,
"name": "RichardHymns",
"department": "Sound",
"job": "SoundEditor",
"profile_path": null
},
{
"id": 7467,
"name": "DavidFincher",
"department": "Directing",
"job": "Director",
"profile_path": "/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"
},
{
"id": 7468,
"name": "ChuckPalahniuk",
"department": "Writing",
"job": "Novel",
"profile_path": "/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"
}
]
} };

How to loop inside a json file with javascript?

I have a json file returned on my javascript code. The file looks like this :
{
"data": [
{
"id": "594984240522886",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Ducks",
"description": "ducks",
"link": "http://www.facebook.com/album.php?fbid=594984240522886&id=593959083958735&aid=1073741834",
"cover_photo": "594984260522884",
"count": 4,
"type": "normal",
"created_time": "2013-06-13T15:12:22+0000",
"updated_time": "2013-06-13T15:12:40+0000",
"can_upload": false
},
{
"id": "593963787291598",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Profile Pictures",
"link": "http://www.facebook.com/album.php?fbid=593963787291598&id=593959083958735&aid=1073741832",
"cover_photo": "593963797291597",
"count": 1,
"type": "profile",
"created_time": "2013-06-11T16:52:29+0000",
"updated_time": "2013-06-11T16:52:31+0000",
"can_upload": false
},
{
"id": "593963467291630",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Goats",
"description": "goats",
"link": "http://www.facebook.com/album.php?fbid=593963467291630&id=593959083958735&aid=1073741831",
"cover_photo": "593963477291629",
"count": 7,
"type": "normal",
"created_time": "2013-06-11T16:51:56+0000",
"updated_time": "2013-06-11T16:52:02+0000",
"can_upload": false
},
{
"id": "593962700625040",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Dogs",
"description": "dogs",
"link": "http://www.facebook.com/album.php?fbid=593962700625040&id=593959083958735&aid=1073741830",
"cover_photo": "593962710625039",
"count": 10,
"type": "normal",
"created_time": "2013-06-11T16:50:27+0000",
"updated_time": "2013-06-11T16:50:37+0000",
"can_upload": false
},
{
"id": "593961937291783",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Cows",
"description": "Cows",
"link": "http://www.facebook.com/album.php?fbid=593961937291783&id=593959083958735&aid=1073741829",
"cover_photo": "593961983958445",
"count": 5,
"type": "normal",
"created_time": "2013-06-11T16:48:26+0000",
"updated_time": "2013-06-11T16:49:32+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NTkzOTYxOTM3MjkxNzgz",
"before": "NTk0OTg0MjQwNTIyODg2"
}
}
}
I would like to loop inside the "data" and see how many different data elements exist(as you see each element has an id , from , name , description..) . How can i do that with javascript?
You can try the following code:
for(i=0;json.data.length;i++){
var element = json.data[i];
}
or also in this other way:
for (i in json.data) {
if (json.data.hasOwnProperty(i)) {
var element = json.data[i];
}
}

Categories