I want to retrieve a specific data from my object stored in local storage using angular. Here is my Object:
{
"user":{
"login":"lara",
"grade":"A"
},
"profiles":[
{
"profile":"admin",
"application":"management",
}
]
}
I want to retrieve profile information (admin) from the list of profiles.
I tried using localStorage.getItem().
setItem in local storage
const data = { your data object here }
SET ITEM
localStorage.setItem("data", JSON.stringify(data));
GET ITEM
let val = JSON.parse(localStorage.getItem('data')).profiles[0].profile;
console.log({val});
You can try with this solution
let data = {
"user": {
"login": "lara",
"grade": "A"
},
"profiles": [
{
"profile": "admin",
"application": "management",
}
]
}
for set data in local storage
localStorage.setItem("data", JSON.stringify(data));
for getting data from local storage
let val = JSON.parse(localStorage.getItem('data'));
if (val) {
let adminProfile = val.profiles.find((data) => data.profile == "admin");
console.log(adminProfile);
}
Try by this..
Use this while storing:
var data = {
"user":{
"login":"lara",
"grade":"A"
},
"profiles":[
{
"profile":"admin",
"application":"management",
}
]
}
localStorage.setItem("data", JSON.stringify(data));
while getting:
let val = JSON.parse(localStorage.getItem('data'));
let profile = val.profiles[0].profile;
Related
I am working on a script in Google Sheets to import JSON data via API and need to be able to parse the data into columns in a spreadsheet. The API is returning a multi-dimensional array with a key that is a randomly generated ID.
{
"log":{
"5DUA3NAuET1O7TDhIvmC":{
"log":4440,
"title":"Trade money outgoing",
"timestamp":1649773788,
"category":"Trades",
"data":{
"user":282048,
"trade_id":"[view]",
"money":39562944
},
"params":{
}
}
}
}
How can I
Parse the data into a multidimensional object
Access the values like title, data.cost, etc to be able to import this data to a sheet?
Try
var result = []
function test(){
jsonString = `{
"log":{
"5DUA3NAuET1O7TDhIvmC":{
"log":4440,
"title":"Trade money outgoing",
"timestamp":1649773788,
"category":"Trades",
"data":{
"user":282048,
"trade_id":"[view]",
"money":39562944
},
"params":{
}
}
}
}`
let json= JSON.parse(jsonString.replace(/(\r\n|\n|\r|\t| )/gm,""))
getMyData(json)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('test').getRange(1,1,result.length,result[0].length).setValues(result)
}
function getMyData(obj) {
for (let p in obj) {
if (obj[p]!=null){
if (typeof obj[p] != 'object' && typeof obj[p] != 'function'){
result.push([p, obj[p]]);
}
if (typeof obj[p] == 'object') {
result.push([p, '']);
getMyData( obj[p] );
}
}
}
}
var response = {
"log": {
"5DUA3NAuET1O7TDhIvmC": {
"log": 4440,
"title": "Trade money outgoing",
"timestamp": 1649773788,
"category": "Trades",
"data": {
"user": 282048,
"trade_id": "[view]",
"money": 39562944
},
"params": { }
}
}
}
var key = Object.keys(response.log)[0];
console.log(key);
var obj = response.log[key];
console.log(obj.title);
console.log(obj.data.user);
This is my code
{
key: "id-16263358905-23",
params: { "3067": 1 },
routeName: "Details"
};
I want to "params":{} ==>
{
key: "id-16263358905-23",
params: {},
routeName: "Details"
};
Please, help me
let obj = {"key": "id-16263358905-23", "params": {"3067": 1}, "routeName": "Details"}
let newObj = {...obj,params:{}}
you can do this, but over here the main question is from where you are getting that object, as per that we have to change the logic what i have mentioned above is simple common logic to update object value.
You can delete the params data as below:
useFocusEffect(useCallback(() => {
if (route.params) {
const keys = Object.keys(route.params)
if (keys && keys.length > 0) {
const removeableKey = keys[0]
delete route.params[removeableKey] // save data before deleting the params
}
}
}, [route.params]))
Here I am trying to modify my data over the iteration and send some result to API call.
The API Call receives a request with a structured data format which is
{ list: [{ id: "1", name: "Hello" }, ... ] }
Somehow I managed to call the API with single data ( const params in my current code, it only accepts single data).
But now it has to be done with multiple data something like this:
{ list: [{ id: "1", name: "Hello" }, { id: "22", name: "Ed" }, { id: "36", name: "Jason" } ... ] }
Here is my current code
const [table, setTalbe] = useState(..); // assume, we have some table data here
const processNow = () => {
let id = 0;
let name = '';
// if table length is greater than 1, we go for the loop.
if (table.length >= 1) {
table.map(data => {
id = data.userId;
name = data.userName;
});
//insert table data to params, here I want to add whole table data into "list"
//the final result of this list should be something like this
//ex ) list: [{ id: '123', name: 'Josh' }, { id: '125', name: 'Sue' }, { id: '2222', name: 'Paker' } ...],
// but how??
const params: any = {
list: [
{
id: id,
name: name
},
],
};
//send PUT reqeust with params
axios
.put(
'/api/v1/tosent',
params,
)
.then(res => {
console.log('The response', res);
})
.catch(err => {
console.log('The error: ', err);
});
}
};
but I'm stuck with it, please help me to finish this code to work properly.
need your kind advice.
Array.prototype.map returns a new array with the function you pass applied to every element. You should study the MDN documentation on map to understand its use.
Your current code does nothing with the map return value:
table.map(data => {
id = data.userId;
name = data.userName;
});
You probably assumed .map would mutate the data, as in change it in place. Instead, the whole operation returns a new array.
It looks like you want to do:
const list = table.map(data => {
return {
id: data.userId,
name: data.userName
}
});
This is applying a function to every element in the array that will map each element to a new object, matching your question, with an id and name key. Then it looks like you want to pass the returned value of map (which we named list above) to your call:
const params: any = {
list: list
};
I made an http request and got back e.g the below json. I want to read the cars and the shoes objects into separate arrays at the time of the http request.
json
{
"id": 9,
"name": "Zlatan",
"cars": [
{
"type": "ford",
"year": "2019"
},
{
"type": "audi",
"year": "2017"
}
]
"shoes": [
{
"brand": "adidas",
"status": "old"
},
{
"brand": "timberland",
"status": "new"
}
]
}
comp.ts
cars = [];
shoes = [];
//......
getZlatan() {
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars ....//what to add here
this.shoes ....// here too.
} );
}
Or is there a cleaner way to load the arrays at http request?
Access the cars and shoes properties of the data with simple dot-notation. It might be ideal to check if the data returned is not null with if(condition here) and then perform your logic. If you have more objects and want to bring all cars and shoes under one array then you have to loop through.
getZlatan() {
return this.httpService.getInfo()
.subscribe(data => {
this.objZlatan = data;
this.cars = this.objZlatan.cars;
this.shoes = this.objZlatan.shoes;
});
}
Just use . and type names to access cars and shoes. Let me show an example:
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars = data.cars;
this.shoes =data.shoes;
} );
I have JSON object in the below format,
$scope.indexData = {
"custid": "1",
"addresses": [
{
"addressType": "P",
"address1": ""
},
{
"addressType": "M"
}
],
"personalDetails": {
"title": "",
"name": ""
}
}
I want to store the object using HTML5 indexDB. how do i store the object?
I tried in the following way, but no luck.
var db;
var request = window.indexedDB.open("newDatabase", 1);
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("customers");
for (var i in $scope.indexData) {
objectStore.add($scope.indexData[i]);
}
}
I am getting the following error saying: Uncaught DataError: Failed to execute 'add' on 'IDBObjectStore': The object store uses out-of-line keys and has no key generator and the key parameter was not provided.
You are specifying a keypath which instruct the store to use in-line keys. your code maybe like this:
var db;
var request = window.indexedDB.open("newDatabase", 1);
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("customers",{keyPath: "isbn"});
for (var i in $scope.indexData) {
objectStore.add({i:$scope.indexData[i], isbn:i});
}
}