How to properly create objects instead of arrays in Javascript - javascript

I am trying to create a object using my placeholder. The current code works however it is creating array in my Children property. How can I recode so that my output is object
const placeholder = (index, isRootDirectory) => {
const create = {
id: index,
title: null,
location: index,
isRootDirectory,
padStyle: [
{
icon: null,
color: null,
},
],
UUID: null,
action: null,
Children: [],
};
return create;
};
const createLayout = () => {
let root = {
info: "Custom Layout",
Children: [],
};
for (let i = 0; i < 2; i++) {
root.Children.push(placeholder(i, true));
console.log(root);
}
console.log(root);
};
Current output:
{"Children": [{"Children": [Array], "UUID": null, "action": null, "id": 0, "isRootDirectory": true, "location": 0, "padStyle": [Array], "title": null}, {"Children": [Array], "UUID": null, "action": null, "id": 1, "isRootDirectory": true, "location": 1, "padStyle": [Array], "title": null}], "info": "Custom Layout"}
Desired output
{"Children": [{"Children": [object], "UUID": null, "action": null, "id": 0, "isRootDirectory": true, "location": 0, "padStyle": [object], "title": null}, {"Children": [object], "UUID": null, "action": null, "id": 1, "isRootDirectory": true, "location": 1, "padStyle": [object], "title": null}], "info": "Custom Layout"}

In your code where you defined the constant create, you defined the Children key as an array by writing Children: []. Instead, write Children: {}.
So
const create = {
id: index,
title: null,
location: index,
isRootDirectory,
padStyle: [
{
icon: null,
color: null,
},
],
UUID: null,
action: null,
Children: [],
};
Would be written as
const create = {
id: index,
title: null,
location: index,
isRootDirectory,
padStyle: [
{
icon: null,
color: null,
},
],
UUID: null,
action: null,
Children: {},
};

Related

Fetching information from Roblox API about a game

I am trying to fetch information from: https://games.roblox.com/v1/games?universeIds=3759152694
But having it try to response with "response.data[0]" (I use jsonpathfinder) it gives me undefined. When I try to do "response.data[0].id" it says that id is not defined. I have not messed with apis in quite a while so I may be just missing something here. Any help is appreciated!
const axios = require("axios");
module.exports = {
name: "info",
execute: async (bot, message, args) => {
test = {
data: [
{
id: 3759152694,
rootPlaceId: 10269801695,
name: "unnamed sim",
description: "soon",
sourceName: "unnamed sim",
sourceDescription: "soon",
creator: { id: 3593901883, name: "Jack1286401", type: "User", isRNVAccount: false, hasVerifiedBadge: false },
price: null,
allowedGearGenres: ["All"],
allowedGearCategories: [],
isGenreEnforced: false,
copyingAllowed: false,
playing: 0,
visits: 0,
maxPlayers: 6,
created: "2022-07-18T14:21:46.03Z",
updated: "2022-07-22T08:17:08.8213451Z",
studioAccessToApisAllowed: false,
createVipServersAllowed: false,
universeAvatarType: "MorphToR15",
genre: "All",
isAllGenre: true,
isFavoritedByUser: false,
favoritedCount: 0,
},
],
};
await axios.get("https://games.roblox.com/v1/games?universeIds=3759152694").then(function (response) {
// handle success
console.log(JSON.stringify(response.data[0]));
});
},
};
JSON Table:
{
"data": [
{
"id": 3759152694,
"rootPlaceId": 10269801695,
"name": "unnamed sim",
"description": "soon",
"sourceName": "unnamed sim",
"sourceDescription": "soon",
"creator": { "id": 3593901883, "name": "Jack1286401", "type": "User", "isRNVAccount": false, "hasVerifiedBadge": false },
"price": null,
"allowedGearGenres": ["All"],
"allowedGearCategories": [],
"isGenreEnforced": false,
"copyingAllowed": false,
"playing": 0,
"visits": 0,
"maxPlayers": 6,
"created": "2022-07-18T14:21:46.03Z",
"updated": "2022-07-22T08:17:08.8213451Z",
"studioAccessToApisAllowed": false,
"createVipServersAllowed": false,
"universeAvatarType": "MorphToR15",
"genre": "All",
"isAllGenre": true,
"isFavoritedByUser": false,
"favoritedCount": 0
}
]
}

Parse data from one format to another Typescript

I need to parse some data got from BE from one format to another to can inject it into a table component. The format received is:
{
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123,
"children": []
}
]
}
]
}
and I need the following format:
{
"key": "Income",
"data": {
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null
},
"children": [
{
"key": "4000 Revenue",
"data": {
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null
},
"children": [
{
"key": "4100 Product 1 Revenue",
"data": {
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123
},
"children": []
}
]
}
]
}
Each parent can have more children or no children.
I tried to do something with reduce, but no result. This is what I've tried:
const prepareTableValue = (data: any): any => {
const res = data.reduce((result: any, node) => {
if (node.children) {
result.push({
key: node.displayName,
data: {
displayName: node.displayName,
baseBersionSum: node.baseVersionSum,
comparisonVersionSum: node.comparisonVersionSum,
variance: node.variance,
variancePercent: node.variancePercent,
},
children: node.children,
});
prepareTableValue(node.children);
}
return result;
}, []);
return res;
};
Thanks in advance!
Nice challenge ! Here is a solution with a recursive function that creates a new object and adds to it recursively by going through each child of the initial object and calling itself for that child and the child in that position in the new object:
const objToFormat = {
"displayName": "Income",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4000 Revenue",
"baseVersionSum": null,
"comparisonVersionSum": null,
"variance": null,
"variancePercent": null,
"children": [
{
"displayName": "4100 Product 1 Revenue",
"baseVersionSum": -1000000,
"comparisonVersionSum": 4300000,
"variance": -5300000,
"variancePercent": -123,
"children": []
}
]
}
]
};
const formatData = (objToFormat, formattedObj = {}) => {
const { displayName, children, ...data } = objToFormat;
formattedObj.key = displayName;
formattedObj.data = { displayName, ...data };
formattedObj.children = [];
children.forEach((child, i) => {
formattedObj.children[i] = {};
formatData(child, formattedObj.children[i]);
})
return formattedObj;
}
console.log(formatData(objToFormat))
A recursive parse should work.
function parseData(items: any[]) {
const parsed = items.map((item) => {
const clone = Object.create(item);
clone.key = clone.displayName;
clone.data = {
displayName: clone.displayName,
baseBersionSum: clone.baseVersionSum,
comparisonVersionSum: clone.comparisonVersionSum,
variance: clone.variance,
variancePercent: clone.variancePercent,
};
clone.children = parseData(clone.children);
return clone;
});
return parsed;
}

How to add an 'id' to json file at first line. [javascript][node.js]

I found a working script to add an id to each object;
function addId(id) {
return function iter(o) {
if ('fediverse' in o) {
o.id = id++;
}
Object.keys(o).forEach(function (k) {
Array.isArray(o[k]) && o[k].forEach(iter);
});
};
}
var data = [{"fediverse": "#username#mastodon.online", "name": "alternatenamehere", "alternate_names": "", "gender": "", "category": "", "description": "description here.", "link": "https://mastodon.online/users/username", "image": "https://files.mastodon.online/accounts/avatars/image.jpg", "language": "", "region": "", "user": true, "group": false, "creator": false, "companyOrganization": false, "project": false, "applicationSoftware": false}];
data.forEach(addId(1))
console.dir(data, {depth: null, colors: true, maxArrayLength: null});
This script outputs;
[
{
fediverse: '#username#mastodon.online',
name: 'alternatenamehere',
alternate_names: '',
gender: '',
category: '',
description: 'description here.',
link: 'https://mastodon.online/users/username',
image: 'https://files.mastodon.online/accounts/avatars/image.jpg',
language: '',
region: '',
user: true,
group: false,
creator: false,
companyOrganization: false,
project: false,
applicationSoftware: false,
id: 1
}
]
the problem is the search I use detects ids from the first line only. how can I add the id at the first line instead of the last line?

Convert key value pair from one single keys array with different arrays of values

I need to convert key value pair of json to use in ejs table iterate.
I converted key value pairs as each key - value as object which is not iterable.
Here data.metaData are keys and data.rows are values to map.
var data = {
metaData: [{
name: "SCHEDULED_TIME"
},
{
name: "TRIGGER_TIME"
},
{
name: "START_TIME"
},
{
name: "END_TIME"
},
{
name: "CEC_ID"
},
{
name: "TRIGGER_TYPE"
},
{
name: "STATUS"
},
{
name: "JOB_NAME"
},
],
rows: [
[
"12:20",
null,
null,
null,
null,
null,
null,
"CLARITY_ETL",
],
[
"15:50",
null,
null,
null,
null,
null,
null,
"CLARITY_ETL",
],
[
"18:30",
null,
null,
null,
null,
null,
null,
"BUDGET_ETL",
],
]
}
**
Expected result as: **
data = [{
"SCHEDULED_TIME": "12:20",
"TRIGGER_TIME": null,
"START_TIME": null,
"END_TIME": null,
"CEC_ID": null,
"TRIGGER_TYPE": null,
"STATUS": null,
"JOB_NAME": "CLARITY_ETL",
}, {
"SCHEDULED_TIME": "15:50",
"TRIGGER_TIME": null,
"START_TIME": null,
"END_TIME": null,
"CEC_ID": null,
"TRIGGER_TYPE": null,
"STATUS": null,
"JOB_NAME": "CLARITY_ETL",
}, {
"SCHEDULED_TIME": "18:30",
"TRIGGER_TIME": null,
"START_TIME": null,
"END_TIME": null,
"CEC_ID": null,
"TRIGGER_TYPE": null,
"STATUS": null,
"JOB_NAME": "BUDGET_ETL",
}]
One possible solution is to use Array.map() over the rows, to map each row to an object, the keys of the generated object will come from the metaData:
var data = {
metaData: [
{name: "SCHEDULED_TIME"},
{name: "TRIGGER_TIME"},
{name: "START_TIME"},
{name: "END_TIME"},
{name: "CEC_ID"},
{name: "TRIGGER_TYPE"},
{name: "STATUS"},
{name: "JOB_NAME"}
],
rows: [
["12:20", null, null, null, null, null, null, "CLARITY_ETL"],
["15:50", null, null, null, null, null, null, "CLARITY_ETL"],
["18:30", null, null, null, null, null, null, "BUDGET_ETL"]
]
};
let res = data.rows.map((row) =>
{
let obj = {};
row.forEach((val, idx) => obj[data.metaData[idx].name] = val);
return obj;
});
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Or, in a simplified version if you use Array.reduce() too.
var data = {
metaData: [
{name: "SCHEDULED_TIME"},
{name: "TRIGGER_TIME"},
{name: "START_TIME"},
{name: "END_TIME"},
{name: "CEC_ID"},
{name: "TRIGGER_TYPE"},
{name: "STATUS"},
{name: "JOB_NAME"}
],
rows: [
["12:20", null, null, null, null, null, null, "CLARITY_ETL"],
["15:50", null, null, null, null, null, null, "CLARITY_ETL"],
["18:30", null, null, null, null, null, null, "BUDGET_ETL"]
]
};
let res = data.rows.map(
row => row.reduce((o, v, i) => ({...o, [data.metaData[i].name]: v}), {})
);
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

API response in the browser different from the one in the code

Here's my code:
async function BuiltWithCall(website) {
var domainCall = `https://api.builtwith.com/v12/api.json?KEY=${keys.builtWith}&LOOKUP=${website}`;
var domainRes = await fetch(domainCall);
console.log(domainRes);
var keywordCall = `https://api.builtwith.com/kw1/api.json?KEY=${keys.builtWith}&LOOKUP=${website}`;
var keywordRes = await fetch(keywordCall);
console.log(keywordRes);
return await {'domRes': domainRes.json(), 'kwRes': keywordRes.json()};
}
It takes the website provided and runs it through the BuiltWith API. But the problem is the response.
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 7,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
_transformState: [Object] },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'https://api.builtwith.com/v12/api.json?KEY=key&LOOKUP=hotelscombined.com',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object] } } }
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
_writableState: [Object],
writable: false,
allowHalfOpen: true,
_transformState: [Object] },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'https://api.builtwith.com/kw1/api.json?KEY=key&LOOKUP=hotelscombined.com',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object] } } }
So this right here makes no sense to me. Because this is the exact same URL, run in a browser:
{
"Keywords": [
{
"Domain": "hotelscombined.com",
"Keywords": [
"compare",
"save",
"cheap",
"hotel",
"deal",
"hotelscombined",
"search",
"... More keywords but you get the idea"
]
}
],
"Errors": []
};
Other call response:
{
"Results": [
{
"Result": {
"IsDB": true,
"Spend": 609,
"Paths": [
{
"FirstIndexed": 1294059600000,
"LastIndexed": 1526338800000,
"Domain": "builtwith.com",
"Url": "",
"SubDomain": "",
"Technologies": [
{
"Categories": [
"Edge Delivery Network"
],
"IsPremium": "yes",
"Name": "Amazon CloudFront",
"Description": "Amazon CloudFront delivers your static and streaming content using a global network of edge locations.",
"Link": "http://aws.amazon.com/cloudfront/",
"Tag": "cdns",
"FirstDetected": 1386284400000,
"LastDetected": 1526338800000
},
]
},
]
},
"Meta": {
"Vertical": "Technology And Computing",
"Social": [
"http://twitter.com/builtwith",
"http://facebook.com/builtwith",
"http://linkedin.com/company/builtwith",
"http://google.com/+builtwithdotcom"
],
"CompanyName": "BuiltWith",
"Telephones": [
"+61-300-558745",
"+1-650-618-3949"
],
"Emails": [
"support#builtwith.com"
],
"City": "Sydney",
"State": "NSW",
"Postcode": "2000",
"Country": "AU",
"Names": [
{
"Name": "N/A",
"Type": 0,
"Email": "n/a#builtwith.com"
},
{
"Name": "N/A",
"Type": 0,
"Email": "n/a#builtwith.com"
}
],
"ARank": 22108,
"QRank": 275921
},
"Attributes": {
"MJRank": 8737,
"MJTLDRank": 4620,
"RefSN": 7402,
"RefIP": 10142,
"TTFB": 129,
"Sitemap": 20,
"GTMTags": 0,
"QubitTags": 0,
"TealiumTags": 0,
"AdobeTags": 0,
"CDimensions": 0,
"CGoals": 0,
"CMetrics": 0,
"SourceBytes": 0
},
"FirstIndexed": 1294059600000,
"LastIndexed": 1526338800000,
"Lookup": "builtwith.com"
}
],
"Errors": []
}
So as you can see the responses are completely different, and I have no idea why. The same fetch method works perfectly for PageSpeed API, but here something is going horribly wrong.
PageSpeed call:
async function PageSpeedCall(website) {
var pagespeedCall = `https://www.googleapis.com/pagespeedonline/v4/runPagespeed?url=https://${website}&strategy=mobile&key=${keys.pageSpeed}`;
// second call
var results = await fetch(pagespeedCall);
return await results.json();
}
What am I doing wrong?
domainRes is a Response object, not a payload. That is why you see all the stuff in the console output.
To parse the payload as JSON you need to call domainRes.json which also gives you a promise so you have to await for it. Like this.
async function BuiltWithCall(website) {
var domainCall = `https://api.builtwith.com/v12/api.json?KEY=${keys.builtWith}&LOOKUP=${website}`;
var domainRes = await fetch(domainCall);
console.log(domainRes);
var keywordCall = `https://api.builtwith.com/kw1/api.json?KEY=${keys.builtWith}&LOOKUP=${website}`;
var keywordRes = await fetch(keywordCall);
console.log(keywordRes);
return {'domRes': await domainRes.json(), 'kwRes': await keywordRes.json()};
}

Categories

Resources