Storing Object Inside a Variable from API JavaScript

Store fetched data from API in a variable and use it for the rest of the code

While await looks synchronous all it does is allow the promise (a promise that data will or not be delivered in the future) to resolve or reject. So you can't immediately assign a variable to data that doesn't exist yet.

The JS event loop is basically a queuing system. Things go in, and some events get resolved immediately and removed from the queue (mouse events, for example), but promises take time, but when they're complete then they get removed from the queue. But while that's happening other events are popped off, so events don't stop happening.

So, while you're still learning about how promises work, maybe set up a control function that awaits the data and then runs a new function that creates the chart with that data.

const data = '["data"]';

function mockApi() {
return new Promise((res, rej) => {
setTimeout(() => res(data), 1000)
});
}

async function main() {
const data = await mockApi()
showData(JSON.parse(data));
}

function showData(data) {
console.log(data);
}

main();

Javascript Fetch API - How to save output to variable as an Object (not the Promise)

.json() is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then()

var obj;

fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => obj = data)
.then(() => console.log(obj))

Store object from API to state

You may try

//ComponentDidMount happen here
.then(result => {
first.setState(result.data.data.a);
second.setState(result.data.data.b);
third.setState(result.data.data.c);
}
debugger;
})

How to store objects in HTML5 localStorage

Looking at the Apple, Mozilla and Mozilla again documentation, the functionality seems to be limited to handle only string key/value pairs.

A workaround can be to stringify your object before storing it, and later parse it when you retrieve it:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

How to store the values of a JSON response to an API Call in as many variables as the (unknown) number of objects using node.js

I got an answer in another forum so I thought I could paste it here for the help of the community.

original answer: https://community.hubspot.com/t5/APIs-Integrations/How-to-use-the-values-of-a-JSON-response-from-an-external/m-p/269841#M24366

In order to just get the data you need from what's being returned back to you, you can use some higher order functions such as map:

great youtube video on this: https://www.youtube.com/watch?v=rRgD1yVwIvE

MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

For example, if you have this data structure:

[
{
"id": "my-awesome-program2",
"currency": "USD",
"title": "My awesome program 2",
"cookie_time": 45,
"default_landing_page_url": "https://my-site.com"
},
{
"id": "my-awesome-program1",
"currency": "USD",
"title": "My awesome program 1",
"cookie_time": 45,
"default_landing_page_url": "https://my-site.com"
}
]

you can use this code to map the objects into something more useful to you. First you can assign the data to a variable:

const myData = [
{
"id": "my-awesome-program2",
"currency": "USD",
"title": "My awesome program 2",
"cookie_time": 45,
"default_landing_page_url": "https://my-site.com"
},
{
"id": "my-awesome-program1",
"currency": "USD",
"title": "My awesome program 1",
"cookie_time": 45,
"default_landing_page_url": "https://my-site.com"
}
]

Then we can map over the data and assign it to a new variable or return it from a function:

const newData = myData.map(item => ({
id: item.id,
title: item.title
}))

// returns
// [
// {
// "id": "my-awesome-program2",
// "title": "My awesome program 2"
// },
// {
// "id": "my-awesome-program1",
// "title": "My awesome program 1"
// }
// ]

After this, if you need each item to then make a call to Hubspot, you can do that with whatever library you want like this:

   axios.post(url, config, item).then(res => {
console.log("...Done!")
})
});

It'd be best to put this code in a separate function after you've returned all of the data you need in order to ensure that all the data is there. I'd also recommend limiting your calls per second so you don't hit the X/s rate limit of the API. A good package for that is called bottleneck on NPM.

Storing JSON Object to variable

you can make use of array and push value into it and join array

var k_val = [];
var v_val = [];
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
k_val.push(k)
v_val.push(v)
console.log(k);
console.log(v);
});
});
var k_values= k_val.join();
var v_values= v_val.join();
console.log(k_values);
console.log(v_values);


Related Topics



Leave a reply



Submit