Getting a declared constant array with nested Json values in javascript - javascript

I am not sure if this is possible but here is the question:
I have the declared a constant grabbing partially an API's response body.
For simplicity, I will declare the partial API response as follows:
const partialResponse = {
"Name": "Marshall",
"Color": "Blue",
}
I am declaring a constant based on a array which includes the API's response body (stringified).
const data = {
"id": "123",
"jsonValues": partialResponse
}
However, in my script, the following returns null when I am expecting "Marshall" as an output:
console.log(data.jsonValues.Name)

Related

How to extract data from an object API response Apps script goole sheets

//I want to achieve "highestBid": "94628.41" displayed in A3 cell - the value of highestBid varies with time.
function response() {
var url = "https://api.zonda.exchange/rest/trading/ticker/BTC-PLN";
var response = UrlFetchApp.fetch("https://api.zonda.exchange/rest/trading/ticker/BTC-PLN");
var obj = { highestBid: "94628.41" };
type: "Fixed Multiple";
Status: "Active";
var result = Object.keys(obj).map((key) => [key, obj[key]]);
Logger.log(result);
SpreadsheetApp.getActiveSheet().getRange("A3").setValue(result);
}
The most important thing for you to do is to get the response body as a string using getContentText() and parse it as JSON using JSON.parse() so you can access the values easily in JavaScript following the structure of the returned data:
{
"status": "Ok",
"ticker": {
"market": {
"code": "BTC-PLN",
"first": { "currency": "BTC", "minOffer": "0.0000468", "scale": 8 },
"second": { "currency": "PLN", "minOffer": "5", "scale": 2 },
"amountPrecision": 8,
"pricePrecision": 2,
"ratePrecision": 2
},
"time": "1663191022379",
"highestBid": "94563.2",
"lowestAsk": "94846.78",
"rate": "94846.78",
"previousRate": "94566.21"
}
}
You should also make some other changes:
use const instead of var to treat values as immutable and you might also be interested in their scope
you should check for the response code using getResponseCode() as if the request fails (which it can for many reasons) you won't be able to access the data or get unexpected data returned. See HTTP status codes - Wikipedia.
For more details on what parsing means and how JSON and JavaScript are connected see this explanation.
Here now how you can set the value of highestBid in cell A3.
function response() {
const url = "https://api.zonda.exchange/rest/trading/ticker/BTC-PLN";
const response = UrlFetchApp.fetch(url);
if(response.getResponseCode != 200){
Logger.log(`The request failed with status code ${response.getResponseCode()}`)
} else {
// get the content of the response body as string (in UTF-8 encoding)
const responseStr = response.getContentText("UTF-8")
// the string is in JSON format so we can now parse it to make it accessible in javascript
const data = JSON.parse(responseStr);
// the hightest bid can now easily be obtained
const highestBid = data.ticker.highestBid;
Logger.log(`The highest bid is ${highestBid} until ${new Date(data.ticker.time).toLocaleString()}`)
// set value in cell A3
SpreadsheetApp.getActiveSheet().getRange("A3").setValue(highestBid);
}
}
By the way: Object.entries(result) returns the same result as var result = Object.keys(obj).map((key) => [key, obj[key]]);.

Modify an array of objects inside an array of objects in js

Hello developers I'm trying to modify an array of objects inside an array of objects before deploying its result to Redux reducer.
The array is obtained through a request to an endpoint, reason why i must to create an instance of writable copy of it , and then proceed on the process
Lest say i have this array:
allProducts= [
{
"product_type": "Bikes",
"product_imgs": [
{
"id": 5,
"url": "Mountain Bike/Screenshot (200)"
},
{
"id": 6,
"url": "Mountain Bike/Screenshot (200)"
}
],
"product_name": "product test 1"
},
{
"product_type": "Bikes",
"product_imgs": [
{
"id": 7,
"url": "City Bike/banderaa"
},
{
"id": 8,
"url": "City Bike/banderaa"
}
],
"product_name": "product test 2"
}
]
I would like to modify the items inside the array product_imgs of each object , but for that , having in mind this array comes from a request , i do create a readable copy an over that i set the logic.
let instance=[...allProducts];
then using a double for each (though i also tried using a doule for loop) i reach till every image inside the array of objects product_imgs of each object :
instance.forEach(array=>array.product_imgs.map(element => {
this.imgDownLoaderFirebase
.ref(element.url)
.getDownloadURL()
.toPromise()
.then((url) => {
console.log(url);
//then in this space once the url of some firebase endpoint is reached and else
//i would like to modify that object inside the array product_imgs which is at the same time
//part of the instance array.
//For that i expose that this new url gotten would be asigned as the new
//value thus
element = { ...element };
element.url=url
console.log(element);
console.log(instance);//Printing the general array in order to check if changes committed
})
})
I want to specify that i use first a foreach and then a map in order to modify the inner array of objects result , but using a double for each doesn't precisely inmprove this situation:
instance.forEach(array=>array.product_imgs.forEach(element => {........
Then checking the logs , the element (item url) inside the array of objects product_imgs of the array of obejcts instance , is modified , but the external array containing the inner modified not
How could i improve this?
Thanks
If your goal is to extract all product_img values from your array, you could try something like the following :
// This line will convert your array of object into an array of array of urls, using a destructuring process
const urls = allProducts.map(({ product_img }) => product_img);
// This line will merge the previous result into a single-level array of urls that you can iterate onto.
const result = [].concat([], ...res);
Edit : I forgot to mention that this process will in fact return an array of objects including your id and url.

Getting values of json array in Mocha JS

I have following issue, this json is returned by api:
"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}
and I need to get names of all variables under products array, how to get them?
That values are constantly changing everyday, so I can not refer to their names
Trying console.log(res.body.menu.categories[i].products.values()); but its not worked.
Any sugesstion how can I get 10432471 and 10432481 from products? Without referring to variable names.
You are able to get that via Object.keys(res.body.menu.categories[i].products)
To get the object properties, the shortest is using Object.keys()
var obj = {"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}}
var properties = Object.keys(obj.products)
console.log(properties)

Object to Array returns undefined

Im trying to convert JS Object to an Array but Array after conversion is undefined.
I initially have JSON but from what I have read it is automatically parsed into JS Object (when I try to parse it, I get SyntaxError: Unexpected token o in JSON at position 1). Also when I console.log(typeof cityList) I get Object.
Initial JSON goes like this:
[
{
"id": 707860,
"name": "Hurzuf",
"country": "UA",
"coord": {
"lon": 34.283333,
"lat": 44.549999
}
},
{
"id": 519188,
"name": "Novinki",
"country": "RU",
"coord": {
"lon": 37.666668,
"lat": 55.683334
}
}
]
I import JSON like this: import cityList from './city.list.json';
I use this code to convert:
const cityListArray = Object.values(cityList);
If I console.log(cityListArray) I get undefined.
I also tried: const cityListArray = Object.keys(cityList).map(i => cityList[i]) but result is the same.
Im not sure where the problem is. Any help would be appreciated!
You don't need to convert anything, since the JSON object is already an array.
You shouldn't check if something is an array with typeof since it returns "object" for arrays.
const a = [];
typeof a; // "object"
You should use the Array.isArray() method instead.

Extract data from API Object in React

I'm trying to retrieve data from an API with the following JSON output and I have a function in react that I call.
I can see the api output in console.log(users) so the data is being passed into the function.
I am trying to output the array contained in "data" but can't seem to access the data.
{
"dataCount": 2,
"data": [
{
"name": "Test review header",
"text": "This is adescription for a test review",
"img": "http://pngimg.com/upload/pigeon_PNG3423.png"
},
{
"name": "Test review header2",
"text": "This is adescription for a test review2",
"img": "http://pngimg.com/upload/pigeon_PNG3422.png"
}
]
}
renderUsers() {
const { users } = this.props;
console.log(users);
Object.keys(users).map(name => users[name])
console.log(users[name]);
};
The data you need to iterate over is present in the data field of users.
When you are using lists you have to specify the key property, to make react keep track of each item in list.
renderUsers() {
const { users } = this.props;
return (
<ul>
{
users.data.map(name => {
<li key={name}>users[name]</li>
})
}
</ul>
)
}
First of all, I don't use react but what you want should be the same in other javascript frameworks.
Are you sure that it is JSON you receive?
We need to be sure that you receive a JSON object and not normal text. Lets say you have a function parseResponse(data). We can call JSON.parse(data) to parse the data param to a json object. It is also possible that you store the result in a variable.
Using the JSON object
When we are sure you have the param parsed to a JSON object, we get it's data. For example, if you want to get the name of the first object in data, you can call:
parsedJson.data[0].name
where parsedJson is the result of JSON.parse(data),
data is an array of objects in the JSON,
0 is the first object in the array
It is possible that you have this kind of function then:
function parseResponse(data) {
var parsedJson = JSON.parse(data);
for(var i = 0; i < parsedJson.data.length; i++) {
console.log(parsedJson.data[i].name);
}
}
see jsfiddle

Categories

Resources