How do I update my array with my object's value? [duplicate] - javascript

This question already has answers here:
How do I update specific key value of the local storage array?
(4 answers)
How to store and update a localStorage key object which has properties of different data types?
(1 answer)
Closed 4 years ago.
myObj is storing the input coming from the user which is pushed to arr which is store in localStorage as a 'data' key. On submit, I want the new values to be added to arr and not overwrite it (in the else part). The following code works but overwrites the old data:
var myObj = {
field1: fname.value,
field2: lname.value,
field3: birth.value,
field4: salary.value,
field5: String(selectedGender),
field6: String(choicesOfHobby),
field7: color.value,
field8: String(choicesCountry),
field9: textArea.value
}
const arr = new Array()
if (window.localStorage.length == 0) {
const arr = JSON.stringify(myObj);
window.localStorage.setItem('data', arr);
} else {
const arr = JSON.stringify(myObj);
window.localStorage.setItem('data', arr);
}

One thing to note is that JSON.stringify returns a string, not an array -- and, conveniently, localStorage stores key/value pairs where the value is a string, so this all works as it's supposed to.
To update the value in localStorage, you could first retrieve it, then modify it however you like, and then store it again. Since you're working with javascript objects, you'll need to use JSON.parse and JSON.stringify to convert back and forth between objects (to work with) and strings (to store).
This pattern looks like:
let retrievedString = localStorage.getItem('data');
let retrievedObject = JSON.parse(retrievedString); // convert string to obj
let oldColor = retrievedObject.field7; // we don't actually use oldColor
let newColor = "#666666";
retrievedObject.field7 = newColor; //change existing property
retrievedObject.field99 = "99"; // add new property
let modifiedString = JSON.stringify(retrievedObject); // ready to store new version
localStorage.setItem('data', modifiedString);
I added more to the code sample to clarify the kinds of things you can do with your retrieved object before converting back to a string and finally replacing the old version in storage.

Your mistakes:
arr, despite its name, isn't an array.
you never recover the saved data
Check the code below to see my take on the problem: (before trying it, you should erase your localStorage)
var myObj = {
field1: fname.value,
field2: lname.value,
field3: birth.value,
field4: salary.value,
field5: String(selectedGender),
field6: String(choicesOfHobby),
field7: color.value,
field8: String(choicesCountry),
field9: textArea.value
}
const array = window.localStorage.data || []; // get your saved array, or create a new one
array.push(myObj); // Add the current item to the array
window.localStorage.setItem('data', JSON.stringify(array)); // save it again
Any further question please just ask

You need to use something like this:
let data = localStorage.getItem('data');
let dataObj = JSON.parse(data);
dataObj[fieldKey] = fieldObj;
localStorage.setItem('data', JSON.stringify(dataObj));

Firstly read localstorage documents how to use it: https://developer.mozilla.org/tr/docs/Web/API/Window/localStorage
You have to push data array to localstorage and push your objects to your data array after getting data array from localstorage. Finally don't forget to set your data array to localstorage again. Your localstorage part code should be like below:
var data = JSON.parse(window.localStorage.getItem("data"));
if(data === null){
data = [];
}
data.push(myObj);
window.localStorage.setItem("data",JSON.stringfy(data));

You just need to use this:
arrInStorage = localStorage.getItem('data') || [];
arr = JSON.parse(arrInStorage);
arr.push(myObj);
localStorage.setItem('data', JSON.stringify(arr));
instead of your if / else statement.

Related

Javascript: How to push key:pair values in Javascript Object which is already created

My question Explanation:
I have a variable of type = new FormData()
It has some key pair values for example.
const _CheckOutData = new FormData(); // Creating FormData object to send mulitpart data
_CheckOutData.append('Name', this._CheckOutForm.get('name').value);//Appending values to the
_CheckOutForm varibale from FormGroup
_CheckOutData.append('Street', this._CheckOutForm.get('street').value);//Appending values to the
_CheckOutForm varibale from FormGroup
_CheckOutData.append('City', this._CheckOutForm.get('city').value);/
I want to save these values in localStorages. when I directly save _ChechOutData to local storage its empty. Snippet of this function is
SaveFormDataToLocalStorage(_CheckOutData){
localStorage.setItem('_CheckOutData',JSON.stringify(_CheckOutData));
}
So getting empty local Storage. I tried a different apporach which actually work but as my Question is I want to push the values from the _CheckOutData (Type FormData) into new object. here is the snippet
_CheckOutData.forEach((key,value)=>{
let Value=key;
let Key=value;
let TemporaryCart={
[Key]:Value
}
this._CartCheckOutData.push(TemporaryCart);
})
So I am Successfully getting all and values and save them into TemporaryCart (type Object). But the Problem is if there are 5 values it is created 5 object in the Array.But I want to creat one Object with 5 values in it.
My Actual Result:
[{Name: "Fazi"}, {Street: "10570 S De Anza Blvd, Cupertino, CA 95014, United States"}]
But What I want
[
{
Name:"Fazi",
Street:"xyz 123",
.
.
.
.
And So One
}
]
Please Help me community: Regards Abdul Rehman
Hi you can try this one to change formdata in object
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
I would try to set the keys of the object this way:
some_list = []
some_object = {}
some_object['new_key_1']=123
some_object['new_key_2']='abc'
some_object
some_list.push(some_object)
will give you
> some_object
{ new_key_1: 123, new_key_2: 'abc' }
> some_list
[ { new_key_1: 123, new_key_2: 'abc' } ]
Because you want to copy one object into another you could also try alternatively:
> target_object = {...some_object, and_another_key:'123.123'}
{ new_key_1: 123, new_key_2: 'abc', and_another_key: '123.123' }
good luck!
A FormData object will look more like an array of arrays than an actual object. That's basically why a FormData object can have more entries with the same key.
So instead of trying to convert the FormData into an object into JSON, try to turn in into an array.
const formDataToJSON = formData => {
const entriesArray = [...formData];
return JSON.stringify(entriesArray);
}
This will first turn the FormData object into an array that looks like this (before the JSON step):
[
["Name", "Fazi"],
["Street", "xyz 123"],
]
This format will keep all the values in the FormData intact, as you could have multiple keys with the same name.
Reversing the process can be done as well.
const JSONtoFormData = json => {
const formData = new FormData();
const entriesArray = JSON.parse(json);
for (const [name, value] of entriesArray) {
formData.append(name, value);
}
return formData;
};

How to extend an array with new array without declaration

I am working on project where I need to maintain an array from json data returned from API, json can have tree, I have following code which is working fine but I wan to remove if conditions before assigning values to array elements
// data contains json
let newArray = []
for(let d in data){
for(let x in data[d]){
if(typeof(newArray[d]) === 'undefined'){
newArray[d] = []
}
if(typeof(newArray[d][data[d][x]['id']]) === 'undefined'){
newArray[d][data[d][x]['id']] = []
}
newArray[d][data[d][x]['id']]['price'] = data[d][x]['price']
newArray[d][data[d][x]['id']]['discount'] = data[d][x]['discount']
}
}
In above code I have to check the array first and declare it as array if its not otherwise it returns undefined error, is there any way to get rid of there conditions and extend array as per requirement ?
You can you new ES6 spread operator like this
newAraay[d] = [...newArray,...Array(data[d][x]['id']),[...Array('price',data[d][x]['price'])]]
Like here in this snippet I am directly doing abc[1][3][4] = "new value" without explicitly initialising them
let abc = [];
abc[1]= [...abc,...Array(3),[...Array(4),'new inserted value']]
console.log(abc);
newArray[d] = newArray[d] || []
You can understand this operation in this post
Or use Lodash Library
https://lodash.com/docs/4.17.11#set

Fetch localstorage value in array

I am saving value in localstorage as shown below
key = profskill , value = "a,b,c"
In my test.ts file, I have declared array but I am unable to fetch the result in it. Code shown below:
getskills: Array<string> = [];
this.getskills = localStorage.getItem("profskill");
but this is giving error:
Type 'string' is not assignable to type 'string[]'
I want to fetch value like this:
console.log(this.getskills[0]);
The LocalStorage can only store strings, not objects or arrays. If you try to store an array, it will automatically be converted to a string. You need to parse it back to an array :
JSON.parse( localStorage.getItem("profskill") )
Since, you want the comma separated value to be represented as a array of strings for this.getskills use split on the value of the localStorage
Here is a sample example
//say we get the value 'a,b,c' from localStorage into the temp variable
//var temp = localStorage.getItem(profskill);
var temp= 'a,b,c';
this.getskills = temp.split(',');
console.log(this.getskills[0]);
localStorage only supports strings. Use JSON.stringify() to set the data in storage and JSON.parse() to get the data from storage and then use split(",") to split the comma separated data.
var obj = "a,b,c";
localStorage.setItem("profskill", JSON.stringify(obj));
var getskills = [];
getskills = JSON.parse(localStorage.getItem("profskill")).split(",");
console.log(getskills[0]);
First get the data from the LocalStorage:
var DataTableValue = JSON.parse(localStorage.getItem('dataTableValue'));
Then, store in an Array:
var tempArray = new Array();
for (var i = 0; i < DTarray.length; i++) {
tempArray.push(DTarray[i]);
}
All data will be stored in the variable tempArray.

Creating a two-dimensional object from a string of values

In JavaScript, how would I create a two-dimensional object from a string of values, in which the first value would be the name, the last is the content, and all other values in between are properties?
For example, I have a string "capitals,Asia,China,Beijing" and I want the code to split this string into four values and create an object capitals["Asia","China"] = "Beijing";.
How could I do that?
In a complete code piece that would look like this:
<script>
Values = "capitals,Asia,China,Beijing";
Values = Values.split(",");
alert(capitals["Asia","China"]);
</script>
I want the alert box to show me the word Beijing.
How could I do that?
JavaScript does not have two-dimensional arrays or objects that you can access using array[index1, index2] as in some other languages. To do this, you have to use nested objects/arrays, such as
capitals["Asian"]["China"]
To create these, you can do something like:
function makeEntry(obj, str) {
const parts = str.split(','); // array of comma-delimited values
const value = parts.pop(); // final value ("Beijing")
const final = parts.pop(); // final property ("China")
// Find nested property, creating empty object if not there.
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (!(parts in obj)) obj[part] = {};
obj = obj[part];
}
// Set final value.
obj[final] = value;
}
const data = {};
makeEntry(data, "capitals,Asian,China,Beijing");
console.log(data);
console.log(data.capitals["Asian"]["China"]);
This code will work even if there are more levels, such as "capitals,Asia,East Asia,China,Beijing".
Note that there is no way to create a variable in JS given a name. Therefore, we provide an initial object, and build the nest structure within it.
Another approach
Another approach is to create a single-level object with keys such as "capitals,Asian,China". That's easier to create, but might be more inconvenient to access. For example, there would be no easy way to find all the Asian capitals. Below, I'm using regexp to pick apart the input into the first part and the final value.
function makeEntry(obj, str) {
const [, key, value] = str.match(/(.*),([^,]+)$/);
obj[key] = value;
}
const data = {};
makeEntry(data, "capitals,Asian,China,Beijing");
console.log(data);
console.log(data["capitals,Asian,China"]);
You can use WeakMap to set the key of the WeakMap object to an object; Array.prototype.shift(), Array.prototype.splice(), Array.prototype.pop() to set the value of the WeakMap object instance.
let Values = "capitals,Asian,China,Beijing";
Values = Values.split(",");
const capitals = {[Values.shift()]:Values.splice(0, 2)};
const wm = new WeakMap;
wm.set(capitals, Values.pop());
console.log(wm.get(capitals));
You can alternatively set the property of an object to the result of JSON.stringify() called on Values.splice(1, 2)
let Values = "capitals,Asian,China,Beijing";
Values = Values.split(",");
const key = JSON.stringify(Values.splice(1, 2));
console.log(key);
const map = {[Values.shift()]:{[key]:Values.pop()}};
console.log(map.capitals[key]);

localStorage Array split

I have a script to put formdata into localStorage. The data saved in an array. I want that the elements in the array where list without brackets and underneath eachother. Does somebody have a hint for me how to do that?
The array and the output in the div looks like this:
[[{"EMail":"testmail#test.com","Salutaion":"Mr","FirstName":"Test","Name":"Testname"},{"EMail":"testy#test.com","Salutaion":"Mrs","FirstName":"Testy","Name":"TestyFemale"}]]
The script to show the array in a div:
var output = '';
for (var key in localStorage) {
output = output+(key + ':' +localStorage[key])+'\n';
}
$('#divtoshowarray').html(output);
https://jsfiddle.net/6x490kot/
Here is the updated code
$(document).ready(function() {
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
localStorage.setItem('testObject', JSON.stringify(testObject));
var output = '';
var objectFromLS = JSON.parse(localStorage.getItem('testObject'));
for (var key in objectFromLS) {
if (objectFromLS.hasOwnProperty(key)) {
output = output+(key + ':<br>' +objectFromLS[key])+'\n';
}
}
$('#divtoshowarray').html(output);
});
Key Points
You want to iterate on testObject data stored in localStorage. So you need to get testObject from localStorage and iterate on it. Please note, localStorage.getItem will return string, so, you need to parse it so as to return a JSON.
Then you need to iterate on the object, to paint key value pair.
For reference - https://jsfiddle.net/6x490kot/1/

Categories

Resources