I have following input json payload,
{
"Products": {
"Product": [
{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}
]
}
}
And now I need to transform it into the following JSON format.
[
{
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"ProductID": 458761,
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"ProductID": 458761,
"S1": "03",
"S2": "08",
"Year": 2008
}
]
Can someone please help me to write a JavaScript to achieve this task. Any help is really appreciated.
EDIT: You changed the question :(
Assuming your original json is stored in a variable named input. This can be done using this code:
var output = input.Products.Product;
ORIGINAL: You can do this using map:
var output = input.Products.Product.map(function(inObj) {
return {
"Designation": inObj.Designation,
"EntryDate": inObj.EntryDate,
"S1": inObj.S1,
"S2": inObj.S2,
"Year": inObj.Year
}
});
This will give you the output you want - an array of objects, with the ProductIDs removed. I'm a bit rusty when it comes to working with object references, but you could possibly shorten this using delete:
var output = input.Products.Product.map(function(inObj) {
var outObj = inObj;
delete outObj.ProductID;
return outObj;
});
This will change the original input values as well though, so i wouldn't recommend it unless you don't plan on using that data again.
var first = {
"Products": {
"Product": [
{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}
]
}
}
then:
var second = first.Products.Product;
To make it exactly like you want:
for(var i = 0; i<second.length; i++){
delete second[i].ProductID;
}
You can use this little function:
var a = {
"Products": {
"Product": [{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
}, {
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}]
}
};
function newJSON(array){
var b = array.Products.Product;
b.forEach(function(e){delete e.ProductID});
return JSON.stringify(b);
}
document.write(newJSON(a));
With underscore:
var result = _.map(data.Products.Products, (product) => {
return _.omit(product, 'ProductID');
});
Related
How can I map and return the values "Title" in React, with a JSON file that contains an ID for each record? For example:
{
"id001": {
"Title": "Title-1",
"Year": "1990",
"Rated": "PG-13"
},
"id002": {
"Title": "Title-2",
"Year": "1999",
"Rated": "PG-13"
},
...
}
Thank you so much!
you will need to import the json file first. some references
const a = {
"id001": {
"Title": "Title-1",
"Year": "1990",
"Rated": "PG-13"
},
"id002": {
"Title": "Title-2",
"Year": "1999",
"Rated": "PG-13"
},
}
const titleArr = Object.keys(a).map(function(key, index) {
return a[key].Title;
});
console.log(titleArr)
I have an array of objects each with a groupName key/value and then an item key with an array of objects as it's value.
I'm trying to use .reduce() with a forEach to iterate over the main array and merge all of the item values into a new Object with a single groupName and an items array containing all the original item values.
Every time I run the function I only get back the first value and I'm trying to figure out what I'm doing wrong.
Current Function:
const testMerge = moviesArray.reduce((acc, curr) => {
const { items } = curr;
items.forEach((el) => (acc[el] = el));
return acc;
}, {});
console.log('Test merge: ', testMergeObjects);
// returns [object Object]: groupName: The Town, year: 2010
moviesArray:
[
{
"groupName": "comedy",
"items": [
{
"name": "I Love You, Man",
"year": "2009"
}
]
},
{
"groupName": "sci fi",
"items": [
{
"name": "The Matrix",
"year": "1999"
},
{
"name": "Looper",
"year": "2012"
}
]
},
{
"groupName": "crime thriller",
"items": [
{
"name": "The Town",
"year": "2010"
}
]
}
]
Desired Result:
[
"groupName": "movies",
"items": [
{
"name": "I Love You, Man",
"year": "2009"
},
{
"name": "The Matrix",
"year": "1999"
},
{
"name": "Looper",
"year": "2012"
},
{
"name": "The Town",
"year": "2010"
}
]
]
You can use array#map and array#concat to merge items in movie array.
const data = [ { "groupName": "comedy", "items": [ { "name": "I Love You, Man", "year": "2009" } ] }, { "groupName": "sci fi", "items": [ { "name": "The Matrix", "year": "1999" }, { "name": "Looper", "year": "2012" } ] }, { "groupName": "crime thriller", "items": [ { "name": "The Town", "year": "2010" } ] } ],
items = [].concat(...data.map(({items}) => items)),
output = { groupName: "movies", items}
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Giving this json data , how can I Modify it to use object de-structuring to get just the dob property of the parameter object, having troubles understanding please
{
"results":[
{
"gender":"female",
"name":{
"title":"ms",
"first":"emily",
"last":"simmons"
},
"location":{
"street":"1514 preston rd",
"city":"mackay",
"state":"victoria",
"postcode":3943,
"coordinates":{
"latitude":"-82.6428",
"longitude":"99.3586"
},
"timezone":{
"offset":"-5:00",
"description":"Eastern Time (US & Canada), Bogota, Lima"
}
},
"email":"emily.simmons#example.com",
"login":{
"uuid":"4db43a8c-f811-4f66-9063-8de9af1b7ff4",
"username":"brownlion857",
"password":"girls",
"salt":"Fff9zzxa",
"md5":"4eb010fc1f3e9f72b6298b75cec001a1",
"sha1":"086f0a1c0db596967033a77df62e21e6d407f647",
"sha256":"d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"
},
"dob":{
"date":"1992-10-20T03:47:03Z",
"age":26
},
"registered":{
"date":"2012-02-25T19:05:12Z",
"age":7
},
"phone":"09-1749-9293",
"cell":"0490-139-057",
"id":{
"name":"TFN",
"value":"338334455"
},
"picture":{
"large":"https://randomuser.me/api/portraits/women/64.jpg",
"medium":"https://randomuser.me/api/portraits/med/women/64.jpg",
"thumbnail":"https://randomuser.me/api/portraits/thumb/women/64.jpg"
},
"nat":"AU"
}
],
"info":{
}
}
I did something like this:
const displayBirthdate = ( {results: [{dob: {date, age } }]}) =>
{
}
Is there a way I can make it simpler to just get the dob parameter for the function?
You can declare your variables using Destructuring assignment:
const json = {"results": [{"gender": "female","name": {"title": "ms","first": "emily","last": "simmons"},"location": {"street": "1514 preston rd","city": "mackay","state": "victoria","postcode": 3943,"coordinates": { "latitude": "-82.6428", "longitude": "99.3586"},"timezone": { "offset": "-5:00", "description": "Eastern Time (US & Canada), Bogota, Lima"}},"email": "emily.simmons#example.com","login": {"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4","username": "brownlion857","password": "girls","salt": "Fff9zzxa","md5": "4eb010fc1f3e9f72b6298b75cec001a1","sha1": "086f0a1c0db596967033a77df62e21e6d407f647","sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"},"dob": {"date": "1992-10-20T03:47:03Z","age": 26},"registered": {"date": "2012-02-25T19:05:12Z","age": 7},"phone": "09-1749-9293","cell": "0490-139-057","id": {"name": "TFN","value": "338334455"},"picture": {"large": "https://randomuser.me/api/portraits/women/64.jpg","medium": "https://randomuser.me/api/portraits/med/women/64.jpg","thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"},"nat": "AU"}],"info": {}};
const {results: [{dob: {date, age}}]} = json;
console.log('date:', date);
console.log('age:', age);
According to the comment:
how would i make it a function parameter, like dob for instance?
const json = {"results": [{"gender": "female","name": {"title": "ms","first": "emily","last": "simmons"},"location": {"street": "1514 preston rd","city": "mackay","state": "victoria","postcode": 3943,"coordinates": { "latitude": "-82.6428", "longitude": "99.3586"},"timezone": { "offset": "-5:00", "description": "Eastern Time (US & Canada), Bogota, Lima"}},"email": "emily.simmons#example.com","login": {"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4","username": "brownlion857","password": "girls","salt": "Fff9zzxa","md5": "4eb010fc1f3e9f72b6298b75cec001a1","sha1": "086f0a1c0db596967033a77df62e21e6d407f647","sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"},"dob": {"date": "1992-10-20T03:47:03Z","age": 26},"registered": {"date": "2012-02-25T19:05:12Z","age": 7},"phone": "09-1749-9293","cell": "0490-139-057","id": {"name": "TFN","value": "338334455"},"picture": {"large": "https://randomuser.me/api/portraits/women/64.jpg","medium": "https://randomuser.me/api/portraits/med/women/64.jpg","thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"},"nat": "AU"}],"info": {}};
const getDate = dob => ({date, age} = dob);
console.log('displayBirthdate:', getDate(json.results[0].dob));
You could combine de-structuring with mapping for more readable code:
const data = {
"results": [{
"gender": "female",
"name": {
"title": "ms",
"first": "emily",
"last": "simmons"
},
"location": {
"street": "1514 preston rd",
"city": "mackay",
"state": "victoria",
"postcode": 3943,
"coordinates": {
"latitude": "-82.6428",
"longitude": "99.3586"
},
"timezone": {
"offset": "-5:00",
"description": "Eastern Time (US & Canada), Bogota, Lima"
}
},
"email": "emily.simmons#example.com",
"login": {
"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4",
"username": "brownlion857",
"password": "girls",
"salt": "Fff9zzxa",
"md5": "4eb010fc1f3e9f72b6298b75cec001a1",
"sha1": "086f0a1c0db596967033a77df62e21e6d407f647",
"sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"
},
"dob": {
"date": "1992-10-20T03:47:03Z",
"age": 26
},
"registered": {
"date": "2012-02-25T19:05:12Z",
"age": 7
},
"phone": "09-1749-9293",
"cell": "0490-139-057",
"id": {
"name": "TFN",
"value": "338334455"
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/64.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/64.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"
},
"nat": "AU"
}],
"info": {}
}
const [ dob ] = data.results.map(item => item.dob)
console.log(dob)
// {date: "1992-10-20T03:47:03Z", age: 26}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to go through each hotel key and go inside rates to retrieve some info, how could I get values of them inside this JSON on JavaScript:
[
{
"auditData": {
"processTime": "1545",
"timestamp": "2016-04-08 04:33:17.145",
"requestHost": "66.226.74.194",
"serverId": "sa37AUX3ROLBLIS.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|1|3|N|||||||||1"
},
"hotel": {
"checkIn": "2016-04-11",
"checkOut": "2016-04-12",
"code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
"zoneCode": 10,
"zoneName": "Downtown",
"latitude": "19.431353",
"longitude": "-99.156457",
"rooms": [
{
"code": "DBL.2D",
"name": "DOBLE DOS CAMAS DOBLES",
"rates": [
{
"rateKey": "20160411|20160412|W|71|87399|DBL.2D|CGW-TODOS1|BB||1~2~1|2|N#-644903865",
"rateClass": "NOR",
"rateType": "BOOKABLE",
"net": "687.31",
"discount": "111.89",
"discountPCT": "14.00",
"sellingRate": "799.20",
"rateComments": "Incluye desayuno americano para adulto y menor\nel hotel no cuenta con aire acondicionado ",
"paymentType": "AT_WEB",
"packaging": false,
"boardCode": "BB",
"boardName": "ALOJAMIENTO Y DESAYUNO",
"cancellationPolicies": [
{
"amount": "799.20",
"from": "2016-04-08T23:59:00-05:00"
}
],
"rateBreakDown": {
"rateDiscounts": [
{
"code": "DN",
"name": "Descuento Niño",
"amount": "-281.68"
}
]
},
"rooms": 1,
"adults": 2,
"children": 1,
"childrenAges": "2",
"offers": [
{
"code": "9001",
"name": "Descuento niños",
"amount": "-281.68"
}
]
}
]
}
],
"totalSellingRate": "799.20",
"totalNet": "687.31",
"currency": "MXN"
}
},
{
"auditData": {
"processTime": "1543",
"timestamp": "2016-04-08 04:33:19.469",
"requestHost": "66.226.74.194",
"serverId": "sa3RKSJACHXE79K.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|3|3|N|||||||||1"
},
"hotel": {
"checkIn": "2016-04-11",
"checkOut": "2016-04-12",
"code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
"zoneCode": 10,
"zoneName": "Downtown",
"latitude": "19.431353",
"longitude": "-99.156457",
"rooms": [
{
"code": "SGL.DB",
"name": "INDIVIDUAL CAMA DOBLE",
"rates": [
{
"rateKey": "20160411|20160412|W|71|87399|SGL.DB|CGW-TODOS1|BB||1~1~1|5|N#-644903865",
"rateClass": "NOR",
"rateType": "BOOKABLE",
"net": "687.31",
"discount": "111.89",
"discountPCT": "14.00",
"sellingRate": "799.20",
"rateComments": "Incluye desayuno americano para adulto y menor\nel hotel no cuenta con aire acondicionado ",
"paymentType": "AT_WEB",
"packaging": false,
"boardCode": "BB",
"boardName": "ALOJAMIENTO Y DESAYUNO",
"cancellationPolicies": [
{
"amount": "799.20",
"from": "2016-04-08T23:59:00-05:00"
}
],
"rateBreakDown": {
"rateDiscounts": [
{
"code": "DN",
"name": "Descuento Niño",
"amount": "-641.98"
}
]
},
"rooms": 1,
"adults": 1,
"children": 1,
"childrenAges": "5",
"offers": [
{
"code": "9001",
"name": "Descuento niños",
"amount": "-641.98"
}
]
}
]
}
],
"totalSellingRate": "799.20",
"totalNet": "687.31",
"currency": "MXN"
}
}
]
I was trying to use for (var key in data), where data is the JSON response from AJAX.
It's an array. You should iterate using a normal for loop, like
for(var i = 0; i < data.length;i++) {
var rooms = data[i].hotel.rooms
for(var j = 0; j < rooms.length; j++) {
var rates = rooms.rates .. //do something with rates, it's also an array
}
}
Use a each loop each time you see a [] the first character in the string is bracket so we do a each we select the child in our case "hotel" using dot notation v.hotel,v.hotel doesn't start with a bracket so we don't need a loop,we go down in the json object until we reach the rates key where we see another braket so we loop and select the child element in our case the rateKey
var obj =[
{
"auditData": {
"processTime": "1545",
"timestamp": "2016-04-08 04:33:17.145",
"requestHost": "66.226.74.194",
"serverId": "sa37AUX3ROLBLIS.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|1|3|N|||||||||1"
},...];
$.each(obj, function(i, v) {
$.each(v.hotel.rooms, function(i1, v1) {
$.each(v1.rates, function(i2, v2) {
console.log(v2.rateKey);
});
})
});
https://jsfiddle.net/78cpwq5g/
Use the Json object.
If suppose the values are stored in JsonObject.
And some values you may want to retrieve.
Eg:- "code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
$(JsonObject).each(function(){
$(this).hotel.code;
$(this).hotel.name;
})
I use $.ajax to get a make a json-request of a php-file.
The JSON-string is NOT built by myself. It is an external API. So I can't chance it in any ways.
The jQuery goes through all 1st dimension entries.
For 'also_known_as' it does also check the 2nd dimension for multiple entries.
The Problem occurs if there isn't any entry in de 2nd dimension.
How can I check if there is at least one 2nd dimension-entry?
I tried
if(typeof results[i].also_known_as[0] === "undefined")
and
if($.type(results[i].also_known_as[0]) === "undefined")
(also without "")
Any ideas?
The JSON looks like this:
[
{
"plot": "Former cop ...",
"genres": [
"Action",
"Crime",
"Thriller"
],
"rated": "PG-13",
"rating": 7.3,
"language": [
"English",
"Portuguese",
"Spanish"
],
"rating_count": 181888,
"country": [
"USA"
],
"release_date": 20110429,
"title": "Fast Five",
"year": 2011,
"filming_locations": "Rice, California, USA",
"imdb_id": "tt1596343",
"directors": [
"Justin Lin"
],
"writers": [
"Chris Morgan",
"Gary Scott Thompson"
],
"actors": [
"Vin Diesel",
"Paul Walker",
"Jordana Brewster",
"Tyrese Gibson",
"Ludacris",
"Matt Schulze",
"Sung Kang",
"Gal Gadot",
"Tego Calderon",
"Don Omar",
"Joaquim de Almeida",
"Dwayne Johnson",
"Elsa Pataky",
"Michael Irby",
"Fernando Chien"
],
"plot_simple": "Dominic ...",
"poster": {
"imdb": "http://ia.media-imdb.com/images/M/MV5BMTUxNTk5MTE0OF5BMl5BanBnXkFtZTcwMjA2NzY3NA##._V1_SY317_CR0,0,214,317_.jpg",
"cover": "http://imdb-poster.b0.upaiyun.com/001/596/343.jpg!cover?_upt=6182835c1382348170"
},
"runtime": [
"130 min"
],
"type": "M",
"imdb_url": "http://www.imdb.com/title/tt1596343/",
"also_known_as": [
{
"country": "Argentina",
"title": "Rápidos y furiosos 5in control"
},
{
"country": "Australia",
"title": "Fast & Furious 5"
},
{
"remarks": [
"Bulgarian title"
],
"country": "Bulgaria",
"title": "Бързи и яростни 5: Удар в Рио"
}
]
},
{
"plot": "Former cop ...",
"genres": [
"Action",
"Crime",
"Thriller"
],
"rated": "PG-13",
"rating": 7.3,
"language": [
"English",
"Portuguese",
"Spanish"
],
"rating_count": 181888,
"country": [
"USA"
],
"release_date": 20110429,
"title": "Fast Five",
"year": 2011,
"filming_locations": "Rice, California, USA",
"imdb_id": "tt1596343",
"directors": [
"Justin Lin"
],
"writers": [
"Chris Morgan",
"Gary Scott Thompson"
],
"actors": [
"Vin Diesel",
"Paul Walker",
"Jordana Brewster",
"Tyrese Gibson",
"Ludacris",
"Matt Schulze",
"Sung Kang",
"Gal Gadot",
"Tego Calderon",
"Don Omar",
"Joaquim de Almeida",
"Dwayne Johnson",
"Elsa Pataky",
"Michael Irby",
"Fernando Chien"
],
"plot_simple": "Dominic ...",
"poster": {
"imdb": "http://ia.media-imdb.com/images/M/MV5BMTUxNTk5MTE0OF5BMl5BanBnXkFtZTcwMjA2NzY3NA##._V1_SY317_CR0,0,214,317_.jpg",
"cover": "http://imdb-poster.b0.upaiyun.com/001/596/343.jpg!cover?_upt=6182835c1382348170"
},
"runtime": [
"130 min"
],
"type": "M",
"imdb_url": "http://www.imdb.com/title/tt1596343/"
}
]
This is a snippet of my jQuery function:
$.each(results, function(i, item) {
var id = results[i].imdb_id;
var title = results[i].title;
var also_known_as = '';
var also_known_as_prio = ''; //1 = Switzerland, 2 = Germany, 3 = Austria ... Geringere Prio -> wichtiger -> Überschreibt weniger wichtige
$.each(results[i].also_known_as, function(ii, iitem) {
switch (results[i].also_known_as[ii].country) {
case 'Switzerland':
also_known_as = results[i].also_known_as[ii].title;
also_known_as_prio = 1;
break;
case 'Germany':
if (also_known_as_prio != 1) {
also_known_as = results[i].also_known_as[ii].title;
also_known_as_prio = 2;
}
break;
case 'Austria':
if (also_known_as_prio != 1 && also_known_as_prio != 2) {
also_known_as = results[i].also_known_as[ii].title;
also_known_as_prio = 3;
}
break;
}
});
});
I think you wanted typeof results[i].also_known_as === "undefined" (without the [0]). Currently the code is trying to look up an element in the array and then check whether that element is undefined; since the array itself is undefined, it errors while trying to look up the array element before it even gets round to checking whether the element is undefined.