how to remove JSON header from the object array - javascript

I have data in this format. This is gamesparks data that is BaaS using for game development.
I am sending this data to the IOS person but he said he can not fetch this type of data so he told me to change the data
This is my actual data
{
"Details": [{
"5d4c2c28dcf224127a30457b": {
"displayName": "ewqeqw"
},
"5d4c4699dcf224127a3045e0": {
"displayName": "mmmmmmmmmm"
}
}]
}
and I need to change data in this format
{
"Details": [{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
},
{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
}
]
}
This is my code:
var group = Spark.getData().group;
var API = Spark.getGameDataService();
var all1 = new Array();
var entry = API.getItem("playerFriends", Spark.getPlayer().getPlayerId());
var friendsList = {};
if (entry.error()) {
Spark.setScriptError("ERROR", error);
Spark.exit();
} else {
var data = entry.document().getData();
if (group === "all") {
for (var friendOBJ in data) {
//Set details of player ID and display name in new friendsList
object
friendsList[friendOBJ] = {};
friendsList[friendOBJ].displayName = data[friendOBJ].displayName;
friendsList[friendOBJ].playerId = data[friendOBJ].playerId;
}
all1.push(friendsList);
} else {
for (var friendOBJ in data) {
if (data[friendOBJ].group === group && data[friendOBJ].status ===
"accepted") {
friendsList[friendOBJ] = {};
friendsList[friendOBJ].displayName = data[friendOBJ].displayName;
}
}
}
Spark.setScriptData("Details", all1);

Can you not just make a function to convert the data into the desired shape? Something like this should work:
function formatData(details) {
var formattedDetails = [];
for (var id in details) {
formattedDetails.push({
ID: id,
displayName: details[id].displayName
});
}
return formattedDetails;
}
var data = {
"Details": [
{
"5d4c2c28dcf224127a30457b": {
"displayName": "ewqeqw"
},
"5d4c4699dcf224127a3045e0": {
"displayName": "mmmmmmmmmm"
}
}
]
};
var formattedData = formatData(data.Details[0])

this is the output you want
{
"Details": [{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
}
}
and this is my code i am explaining each line with comment
var count = 0;
var tmp = { AcceptedFriendList: []}; //make object and inside empty array
for (var friendOBJ in data) { // retrieving data
if(data[friendOBJ].status === "accepted"){ // your condition
var tempObj = {"displayName" :"","playerid": ""}; //this is format you want
tempObj.displayName = data[friendOBJ].displayName; // putting data in spicify format object
tempObj.playerid = data[friendOBJ].ID;
tmp.AcceptedFriendList[count] = tempObj; //assign object back to array
count++; // iterate it so the next data come further.
}}

Related

JSON object return of an array of objects which contains the keys and its values

Boris has a list of all the beers available in his pub, but it's a huge mess. He would like to see the beers grouped by brands. Boris also told you that the Function should return an array of objects which contains the Brand name and an array of beer IDs of that Brand.
JSON file with data:
https://challenge.codingsans.com/beers.json
Output Example:
[
{
"brand": "brandName2",
"beers": [
"beerID3",
"beerID4"
]
},
{
"brand": "brandName1",
"beers": [
"beerID2",
"beerID1"
]
}
]
//
I have done this:
(So basically nothing. I just would like to get some idea how to solve it.)
request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Date Parse
data = JSON.parse(request.responseText);
// Success!
// Arrays
var beerIDs = [];
var beerBrand = [];
// Iteration
for (var key in data) {
beerIDs.push(data[key].id);
beerBrand.push(data[key].brand);
// console.log(beerIDs);
// console.log(beerBrand);
}
console.log(beerIDs);
console.log(beerBrand);
//final list
var finalList = [];
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Try this:
request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Date Parse
data = JSON.parse(request.responseText);
// Success!
const organizedBeers = data.reduce((acc, beers) => {
const findIndex = acc.findIndex(beer => beer.brand === beers.brand)
if(findIndex > -1) {
acc[findIndex].beersId.push(beers.id)
} else {
acc.push({
brand: beers.brand,
beersId: [beers.id],
})
}
return acc;
}, [])
console.log(organizedBeers)
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
So basically, you can create a new array which will be final output(in our case let's say 'aBeerNBrands'). And you can push new object with required properties (like 'brand': string, ids: array) there.
And then you can loop over main array(in your case :'data') element and in nested loop you can check if that brand object is present in new array('aBeerNBrands') or not, if it is present then push the id to ids array present inside aBeerNBrands's object; else create new object inside 'aBeerNBrands' with required properties. Below code works fine for your requirement.
request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
debugger;
if (request.status >= 200 && request.status < 400) {
// Date Parse
data = JSON.parse(request.responseText);
// Success!
// Arrays
var aBeerNBrands = [];
// Iteration
for (var key in data) {
if(aBeerNBrands.length > 0){
for(var key2 in aBeerNBrands){
if(aBeerNBrands[key2].brand === data[key].brand){
aBeerNBrands[key2].ids.push(data[key].id);
break;
}
if(key2 == aBeerNBrands.length - 1 && aBeerNBrands[key2].brand !== data[key].brand){
var oBrandObject = {
brand: data[key].brand,
ids: [data[key].id]
};
aBeerNBrands.push(oBrandObject);
}
}
} else{
var oBrandObject = {
brand: data[key].brand,
ids: [data[key].id]
};
aBeerNBrands.push(oBrandObject);
}
// console.log(beerIDs);
// console.log(beerBrand);
}
console.log(aBeerNBrands);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Follow below steps :
Grouping input array of objects by brand and resulting with an object using Array.reduce() method.
Structuring the output based on the reduced brand object we have.
Working Demo :
const data = [
{
"id": "ccw-1",
"name": "Coding Challenge White",
"brand": "Coding Challenge Brewery"
}, {
"id": "sw-1",
"name": "Share White",
"brand": "Share",
}, {
"id": "bspa-1",
"name": "Beer Sans Pale Ale",
"brand": "Beer Sans Brewery"
}, {
"id": "ccb-1",
"name": "Coding Challenge Brown",
"brand": "Coding Challenge Brewery"
}, {
"id": "ccw-2",
"name": "Coding Challenge Wheat",
"brand": "Coding Challenge Brewery"
}];
// result array
const resultArr = [];
// grouping by brand and resulting with an object using Array.reduce() method
const groupByBrand = data.reduce((group, item) => {
const { brand } = item;
group[brand] = group[brand] ?? [];
group[brand].push(item.id);
return group;
}, {});
// Finally structuring the output based on the brand object we have.
Object.keys(groupByBrand).forEach((item) => {
resultArr.push({
'brand': item,
'beers': groupByBrand[item]
})
})
// Result
console.log(resultArr);

How to create dynamic JSON. Filter data and create appropriate JSON objects key and values pairs

How to create dynamic JSON as per input. Filter data and create appropriate JSON objects key and values pairs
Below is the database.
Below is the code which had tried but won't work...
success: function (data) {
//lenght
data.value.length
// console.log(data);
//HC list JSON
empData = '[';
$.each(data.value, function (index, item) {
var dataLen = data.value.length;
empData += `{`
if (item.STATUS == 'Active') {
if (item.NODE == 'Testing') {
empData += `"DDM_CO2" : {
"DESIGNATION": "${item.DESIGNATION}",
"EMPLOYMENT": "${item.EMPLOYMENT}",
"GENDER": "${item.GENDER}",
"Name1": "${item.Name1}",
"ROLE": "${item.ROLE}"
},`
} else if (item.NODE == 'Devlopment') {
empData += `"GPH" : {
"DESIGNATION": "${item.DESIGNATION}",
"EMPLOYMENT": "${item.EMPLOYMENT}",
"GENDER": "${item.GENDER}",
"Name1": "${item.Name1}",
"ROLE": "${item.ROLE}"
}`
}
}
});
empData += ']';
empData = JSON.parse(empData);
console.log(empData);
//HC list JSON END
},
Something like this should work
function (data) {
//create array to store emp objects
var empData = new Array();
$.each(data.value, function (index, item) {
if (item.STATUS == 'Active') {
if (item.NODE == 'Testing') {
//create custom object
var emp = {
DDM_CO2: {
DESIGNATION: item.DESIGNATION,
EMPLOYMENT: item.EMPLOYMENT
//etc: item.etc
//etc: item.etc
//etc: item.etc
}
};
//add to array
empData.push(emp);
} else if (item.NODE == 'Devlopment') {
var emp = {
GPH: {
DESIGNATION: item.DESIGNATION,
EMPLOYMENT: item.EMPLOYMENT,
GENDER: item.GENDER,
Name1: item.Name1,
ROLE: item.ROLE
}
};
empData.push(emp);
}
}
}

Create Dynamic json in javascript

I want to create a dynamic json string.
Json looks like:
{
"getHostedPaymentPageRequest": {
"merchantAuthentication": {
"name": "x345dsfg",
"transactionKey": "456tyYYUU7876"
},
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "20.00",
"profile": {
"customerProfileId": "123456789"
}
}
}
}
The values in json like name, transactionKey, transactionType, amount, customerProfileId will vary for different users.
I am following this method to create json:
var getHostedPaymentPageRequest = new Object();
var merchantAuthentication = {};
merchantAuthentication.name = "x345dsfg";
merchantAuthentication.transactionKey = "456tyYYUU7876";
var transactionRequest = {};
transactionRequest.transactionType = "";
transactionRequest.amount = "20.00";
var profile = {};
profile.customerProfileId = "123456789";
transactionRequest.profile = profile;
getHostedPaymentPageRequest.merchantAuthentication = merchantAuthentication;
getHostedPaymentPageRequest.transactionRequest = transactionRequest;
getHostedPaymentPageRequest = JSON.stringify(getHostedPaymentPageRequest);
But its not giving back the right values.
How do I make a valid json in the desired format?
The provided code (if we add a console.log on getHostedPaymentPageRequest) displays the following result (which is how it should behave):
{
"merchantAuthentication": {
"name": "x345dsfg",
"transactionKey": "456tyYYUU7876"
},
"transactionRequest": {
"transactionType": "",
"amount": "20.00",
"profile": {
"customerProfileId": "123456789"
}
}
}
The only meaningful difference that I see between this and the expected result is that in your expected result the JSON starts with
{
"getHostedPaymentPageRequest": {
...
}
}
For that you have to wrap your getHostedPaymentPageRequest object in another object. So instead of doing this:
getHostedPaymentPageRequest = JSON.stringify(getHostedPaymentPageRequest);
add braces like this:
getHostedPaymentPageRequest = JSON.stringify({ getHostedPaymentPageRequest });
You can use this as a reference..
I've split the object based on what it's doing and I've obtained two separate objects: merchantAuthentication and transactionRequest. For each object I created a separate function who return an individual object, because in the future you might want to add more fields therefore it will be easier to you to know were to place them :)
function createMerchantAuthObject() {
let merchantAuth = {};
merchantAuth.name = "x345dsfg";
merchantAuth.transactionKey = "456tyYYUU7876"
return merchantAuth;
}
function createTransactionRequestObject() {
let transactionRequest = {};
transactionRequest.transactionType = "authCaptureTransaction"
transactionRequest.amount = "20.00"
transactionRequest.profile = {};
transactionRequest.profile.customerProfileId = "123456789"
return transactionRequest;
}
function getHostedPaymentPageRequest() {
let request = {}
request.getHostedPaymentPageRequest = {}
request.getHostedPaymentPageRequest.merchantAuthentication = createMerchantAuthObject();
request.getHostedPaymentPageRequest.transactionRequest = createTransactionRequestObject();
return request; // used in order to print the whole object
}
const myObject = getHostedPaymentPageRequest();
console.log(myObject);
This solved my problem:
var money=document.getElementById("amount").value;
var customerprofileid = "1926616706";
var merchantAuthentication = {};
merchantAuthentication.name = "ser555";
merchantAuthentication.transactionKey = "fgrtyujjj";
var getHostedPaymentPageRequest = {
"getHostedPaymentPageRequest": {
"merchantAuthentication": {
"name": merchantAuthentication.name,
"transactionKey": merchantAuthentication.transactionKey
},
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": money,
"profile": {
"customerProfileId": customerprofileid
}
},
"hostedPaymentSettings": {
"setting": [ {
"settingName": "hostedPaymentIFrameCommunicatorUrl",
"settingValue": "{\"url\": \"http://localhost:52965/IframeCommunicator.html\"}"
}]
}
}
};
getHostedPaymentPageRequest = JSON.stringify(getHostedPaymentPageRequest);

How to set Object in array typescript

I want to create new array by json data But I have no idea to create Object!
for show to page(loop for)
my json data
"LIBRARIES":{
"LIBRARY":[
{
"status":"available",
"callNumber":"123456"
},
{
"status":"available",
"callNumber":"434356"
}
]
}
and
"search":{
"lsr02":[
"31011103618567",
"31011001644160"
]}
I want to create object to store this data
I want
"NEWDATA":{
"NEW":[
{
"status":"available",
"callNumber":"123456",
"lsr02": "31011103618567" ///set lsr02 to store in NEW
},
{
"status":"available",
"callNumber":"434356"
"lsr02":"31011001644160"
}
]
}
and I try
let details: string[] = [];
for (let x of this.item.LIBRARIES.LIBRARY){
details.push(x);
}
for (let x of this.item.search.lsr02){
details.push(x);
}
console.log(details)
console.log(details) show
{
"status":"available",
"callNumber":"123456"
},
{
"status":"available",
"callNumber":"434356"
}
{
"31011103618567"
},
{
"31011001644160"
}
thanks for your help :)
You are pushing the search objects separately. You need to assign them to appropriate library object. Try this;
this.item = {
"LIBRARIES": {
"LIBRARY": [{
"status": "available",
"callNumber": "123456"
},
{
"status": "available",
"callNumber": "434356"
}
]
},
"search": {
"lsr02": [
"31011103618567",
"31011001644160"
]
}
}
let details = [];
for (let i = 0; i < this.item.LIBRARIES.LIBRARY.length; i++) {
let lib = this.item.LIBRARIES.LIBRARY[i];
lib.lsr02 = this.item.search.lsr02[i]
details.push(lib);
}
console.log(details)
export class NEWDATA {
public status:string;
public callNumber:string;
public lsr02 : string;
constractor(_status : string, _callNumber : string, _lsr02 : string){
this.status = _status;
this.callNumber = _callNumber;
this.lsr02 = _lsr02;
}
}
details : Array<NEWDATA> = [];
for (let i = 0; i < this.item.LIBRARIES.LIBRARY.length; i++) {
details.push(new NEWDATA(this.item.LIBRARIES.LIBRARY[i].status, this.item.LIBRARIES.LIBRARY[i].callNumber, this.item.search.lsr02[i]));
}

Dynamic creation of Json files from array

I want to create multiple JSON files from an array.
Array :
[{
"Reference": "Registration",
"langkey": "REG_LBL",
"English": "Company Registration",
"Japanese": "会社登録"
}, {
"Reference": "Registration",
"langkey": "INFO_LBL",
"English": "Company Information",
"Japanese": "会社情報"
}]
I need to create two JSON files name English and Japanese(it will be dynamic) from above array.
Desired Output
English.json
{
'INFO_LBL' : 'Company Information',
'REG_LBL':'Company Registration'
}
Japanese.json
{
'INFO_LBL' : '会社情報',
'REG_LBL':'会社情報'
}
Code
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
if (key !=='Reference' && key !== 'langkey' ) {
//{'REG_LBL':'Company Registration'}
objects[obj['langkey']] = obj[key];
fs.writeFileSync('lang/' + langkey + '.json', JSON.stringify(objects, null, 2), { encoding: 'utf8' }, function (err) {
if (err)
{ throw err; }
console.log("completed")
});
}
}
}
I am ale to create two JSON files but the content is overwritten by another.Please help to resolve this?
var finalObject = {};//create new object
data.forEach(v => {
var langkey = v.langkey;
Object.keys(v).forEach(val => {
if (val != 'langkey' && val != 'Reference') {
if (finalObject[val]) {//find if language object is already created.If already created insert in it else create new
let data = {};
data[langkey] = v[val]
finalObject[val] = Object.assign(finalObject[val], data)
} else {
finalObject[val] = {};
finalObject[val][langkey] = v[val];
}
}
})
})
Object.keys(finalObject).forEach(key => {
fs.writeFileSync(path.join(__dirname, `/lang/${key}.json`), JSON.stringify(finalObject[key], null, 2), (err) => {
if (err)
{ throw err; }
console.log('completed');
});
})
You have 2 items in your array, and 2 languages both so do you need to have 4 json files? 2 for INFO_LBL (English & japanesh) and 2 for REG_LBL(English & japanesh) ? or do you just need 2 json files for the second item INFO_LBL (English & japanesh) ?
update: bellow is your solution
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
if (key !== 'Reference' && key !== 'langkey') {
var newObject = {};
var path = 'lang/' + key + '.json';
if (fs.existsSync(path)) {
var newObject = JSON.parse(fs.readFileSync(path, 'utf8'));
}
newObject[obj.langkey] = obj[key];
fs.writeFileSync(path, JSON.stringify(newObject, null, 2), { encoding: 'utf8' });
}
}
}
This one works. I created separate objects for each using window['newVariable'];
var myArray =
[{
"Reference": "Registration",
"langkey": "REG_LBL",
"English": "Company Registration",
"Japanese": "会社登録"
}, {
"Reference": "Registration",
"langkey": "INFO_LBL",
"English": "Company Information",
"Japanese": "会社情報"
}];
for(i=0; i<myArray.length; i++){
window['myJSON' + i] = myArray[i];
}
console.log(myJSON0, myJSON1);
Here's what I got, two separate objects
Now all you have to do is stringify to JSON.
If your data is getting overwritten, it would be because of the writeFileSync. You should be using appendFileSync or the a flag for writeFileSync

Categories