I need to get the inner object value in localStorage.i.e object inside the object.
var filter = {
filterWord: null,
userId: null
}
filter.filterWord = listCAO.sortName;
filter.userId = listCAO.currentUser;
listCAO.filterBreadcumText.push(filter);
localStorage.setItem('entityBreadCumText', listCAO.filterBreadcumText);
LocalStorage only holds String pairs: 'string1'='string2'
So when you do localStorage.getItem('string1') it returns 'string2'.
If you want to store a Javascript Object, you need to convert it into a string first. JSON works best for that.
var myObj = [{'name': 'Paul', 'age': 22}, {'name': 'Steve', 'age': 68}];
myStr = JSON.stringify(myObj);
localStorage.setItem('myData', myStr);
Same when you read the data from localStorage
var myStr = localStorage.getItem('myData');
var myObj = JSON.parse(myStr);
var myName = myObj[0].name;
Or in one step
var myName = JSON.parse(localStorage.getItem('myData'))[0].name;
This may be another solution.
You can use it this way.
let obj = JSON.parse(localStorage.getItem('your_settings_name'));
let lobj: YourObject = <YourObject>obj;
If the data is stored as nested objects instead of an array as c14l 's answer, the syntax changes a little bit.
Let's store nested object first:
var myNestedObject = {"token": "Bearer", "profile": {"name":"Mustafa","expires_at":1678013824}};
myNestedStr = JSON.stringify(myNestedObject);
localStorage.setItem('myNestedData', myNestedStr);
Now let's see how to get the "name" from the nested object:
var nestedStr = localStorage.getItem('myNestedData');
var nestedObj = JSON.parse(nestedStr);
var nestedProfile = nestedObj.profile;
var nestedName = nestedProfile.name;
Or we can get "name" with a single line also:
var nestedNameWithOneLine = JSON.parse(localStorage.getItem('myNestedData')).profile.name;
Related
I have an array of custom class and I want to make a change to one of the items in it.
var mainArray = [MainOrder]()
//Now imagine that mainArray has a bunch of different items in it.
struct MainOrder:Codable {
var time:Date?
var order_id:String?
var side:String?
}
What is the best way to do that? Right now I find the index then I move it into a new variable then I delete the item from the array and then add it back again like you see below. But I am sure this is better way to do this.
if let tempIndex = self.mainArray.index(where: {$0.side == "left"}) {
var tempVar = self.mainArray[tempIndex]
tempVar.time = Date()
self.mainArray.remove(at: tempIndex)
self.mainArray.insert(tempVar, at: tempIndex)
}
You just need the following:
if let tempIndex = self.mainArray.index(where: {$0.side == "left"}) {
mainArray[tempIndex].time = Date()
}
Here's a complete example demonstrating that this works:
struct MainOrder:Codable,CustomStringConvertible {
var time:Date?
var order_id:String?
var side:String?
var description: String {
return "time: \(time), order_id: \(order_id), side: \(side)"
}
}
var mainArray = [MainOrder]()
mainArray.append(MainOrder(time: nil, order_id: "hi", side: "left"))
print(mainArray)
if let tempIndex = self.mainArray.index(where: {$0.side == "left"}) {
mainArray[tempIndex].time = Date()
}
print(mainArray)
Output:
[time: nil, order_id: Optional("hi"), side: Optional("left")]
[time: Optional(2018-01-13 01:59:06 +0000), order_id: Optional("hi"), side: Optional("left")]
If you can guarantee there will always be an object in the array with the matching side value, you can force this all into one line:
mainArray[mainArray.index(where: { $0.side == "left" })!].time = Date()
But this will crash if your assumption is wrong. Be safe and do with the if let.
Declare it as class so it will be reference type
class MainOrder:NSObject,Codable {
var time:Date?
var order_id:String?
var side:String?
}
Edit item directly
var tempVar = self.mainArray[tempIndex]
tempVar.time = Date()
I'm trying to delete values of a lot of variables inside an array:
var fbUserID = String()
var fbUserName = String()
var meNickname = String()
var userIDOneSignal = String()
var deleteStrings = [fbUserID, fbUserName, meNickname, userIDOneSignal]
Is it possible to do something in line of this:
for i in deleteStrings {
i.removeAll()//remove all as in remove the values of each variable
}
I've also tried using deleteStrings[i].removeAll()
Due to value semantics you cannot mutate variables (as a pointer) from an array.
Rather than an array use a struct
struct User {
var fbUserID = "12"
var fbUserName = "Foo"
var meNickname = "Baz"
var userIDOneSignal = "123"
mutating func clear()
{
fbUserID = ""
fbUserName = ""
meNickname = ""
userIDOneSignal = ""
}
}
var user = User()
print(user.fbUserID) // "12"
user.clear()
user.fbUserID = ""
print(user.fbUserID) // ""
Simply delete the array elements
deleteStrings.removeAll()
If your class inherits from NSObject, you can use key value coding to access the fields by name:
class User: NSObject {
var fbUserID = String()
var fbUserName = String()
var meNickname = String()
var userIDOneSignal = String()
var deleteStrings = ["fbUserID", "fbUserName", "meNickname", "userIDOneSignal"]
func clearAll() {
deleteStrings.forEach { setValue("", forKey: $0) }
}
}
let user = User()
user.fbUserID = "12345"
user.fbUserName = "Joseph Doe"
user.meNickname = "Joe"
print(user.meNickname) // "Joe"
user.clearAll()
print(user.meNickname) // ""
If you want to delete/remove variable value then use optional otherwise your variable value only gets removed or become non-existence when it goes out of scope.
For Example:
var a: Int? = 5 // it have default value 5
a = nil // Now a have nil which is kind of telling that it contains nothing which is what you want to achieve
Now coming to your question.
Is it possible to do something in line of this:
for i in deleteStrings {
i.removeAll()
}
You are iterating over an array of strings and then for each string, you are trying to remove all the characters. First of all you will get error
error: cannot use mutating member on immutable value: 'i' is a 'let' constant
Even though you will correct is using var it will not achieve what you are trying to do i.e. I want to delete the variables value because still your fbUserID ... all other variables will have copies of the data you initialised with.
Now how to do it?
You can use optional to achieve it.
var fbUserID: String? = String()
var fbUserName: String? = String()
var meNickname: String? = String()
var userIDOneSignal: String? = String()
// To delete you will need to assign them nil
fbUserId = nil
Again, you can't do them over loop because var are of values type and when you add it to the list their copies get added.
I have the follow object:
formData : {
_id: "550de8956e2d0948080e220f"
category: "Tag1"
isFeatured: "Yes"
likeCount: 557
title: "Integrating WordPress with Your Website"
}
I tried JavaScript but it returned a null value:
var arryFormData = Array.prototype.slice.call(formData)
How can I convert formData into an array of just its values, not properties?
As in ...
arryFormData = ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
or if You like to more functional code:
var arr = [];
angular.forEach(obj, function(value, key){
arr.push(value);
});
If you are using underscore.js,
_.values(formData)
// will get ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
See: here
Alternatively:
var res = [];
for (var x in formData){
formData.hasOwnProperty(x) && res.push(formData[x])
}
console.log(res);
In any event, the array elements might not be in the order that you want.
I prefer one line solution with Object.keys() and es6 syntax, until Object.values() is not here
const values = Object.keys(obj).map(it => obj[it])
or in es5
var values = Object.keys(obj).map(function(it) {
return obj[it]
})
I think there's No magic way, you just have to use a for loop:
for (var key in obj) {
values.push(obj[key])
}
To make it angular, you could use angular.forEach I guess...
This is how i have handled in Angular 5 to convert Object into Array as API gives response in JSON Object so we can convert it into array to use it.
let tmepArr = {};
Object.keys(res).forEach( key => {
tmepArr['name'] = [res[key].name];
tmepArr['id'] = [res[key].id];
});
this.marketplaceDropDown = [tmepArr];
I have a array, which has the bunch of object, i would like to filter the object by 'name' value, again i would like to omit those object from another array of object using underscore.
I know that we can do using earch, but i am not getting the proper approach to do this both..
any one help me to do this?
example :
incoming array:
var incomingArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
];
filter keys:
var omit = ['orange' ,'dog'];
//i need to check whether 'orange' or 'dog' are exist, if so..
var filtered = _.filter(incomingArray, function(obj, i){
return obj.name === omit[i]['name'];//this is wrong i need to loop again how?
});
var anotherArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
]
return only the array without the omit like this:
var outgoingArray = [
{"name":"apple"},
{"name":"cat"},
{"name":"egle"} ]
how we could achieve this with proper approach?
demo
You were nearly there! Use indexOf to check that the name does not belong in the omit array:
var filtered = _.filter(incomingArray, function(obj) {
return omit.indexOf(obj.name) == -1;
});
var contact = { varWorkExperiences: [{ Experience: "aaa" },Experience: "bbb"}] };
I have a structure like this. I can use push method like this:
contact.varWorkExperiences.push({ Experience: "ccc"});
but I want to do this paramaticly
I cant do this:
var x = "Experience";
contact.varWorkExperiences.push({ x: "ccc"});
How can I solve this? I have to use push method in function but I can't pass attribute as a parameter.
var x = "Experience";
var obj = {};
obj[x] = "ccc";
contact.varWorkExperiences.push(obj);