how to convert {obj:"{objects}"} into array with json object inside it - javascript

I had % in my cookie and I found following code for it and got the data below after implying that code
var cookies = (document.cookie);
var output = {};
cookies.split(/\s*;\s*/).forEach(function (pair) {
pair = pair.split(/\s*=\s*/);
var name = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair.splice(1).join('='));
output[name] = value;
});
console.log(output);
The data console is down below;
{"objName":"[{"key":1,"key2":"value 123","key3":"value123"},{"key":1,"key2":"value 123","key3":"value123"}]"}
I have the data as shown above, What I want is to objName into array and remove "" from in front of [] array barckets
objName=[{"key":1,"key2":"value 123","key3":"value123"},{"key":1,"key2":"value 123","key3":"value123"}]

As far as I understand, you are trying to get cookie values, you can try this code and handle the returned array as you need. You can try this solution and let me know if it works.
var cookies = document.cookie.split(';').reduce(
(cookies, cookie) => {
const [name, val] = cookie.split('=').map(c => c.trim());
cookies[name] = val;
return cookies;
}, {});
console.log(cookies);

Related

Changing the data of the repeater in wix

I'm trying to manipulate the repeater list in Wix. When the user selects the quantity of equipment, that number of forms show up. I got the hang of it when I see it in the console log but when I try to display it on the web, it gives me an error. I've tried reassigning $w("#repeater1").data to newArr(the new data).
Here's my code
$w("#repeater1").hide();
let itemOptions = $w("#quoteDropdown").options
$w("#quoteDropdown").onChange((event) => {
$w("#repeater1").show();
const arrOfValues = []
let newArr = []
let repeaterData = $w("#repeater1").data;
let quantity = Number(event.target.value);
let iterator = repeaterData.values();
for(const value of iterator) {
arrOfValues.push(value);
}
for(let i = 0 ; i < itemOptions.length; i++) {
newArr = repeaterData.slice(0, quantity);
}
if(quantity > newArr.length) {
let newItems = arrOfValues.filter(arr => {
newArr.forEach(na => arr !== na)
})
newArr.push(newItems)
}
console.log("newArr");
console.log(newArr);
// $w("#repeater1").data is the original data from the repeater
// newArr is the altered data from the repeater based on how it appears based on the users' interaction.
// I've tried each one of these
// $w("#repeater1").data = newArr;
// return newArr;
}); // end onChange
If you're trying to assign the array as the data for a repeater, you need to follow some rules. First, it needs to be an array of objects. Second, each object needs to have an _id property.

How to select specified data like id in a for loop to use those data in different page

I want to get and store id from idArray to use each id indvidual
I tried to store in session storage but it return the last element
success: function (data) {
const myText = "";
const addressArray = [];
const titleArray = [];
const typeArray = [];
const idArray = [];
data.map((user) => {
addressArray.push(user.address);
titleArray.push(user.title);
typeArray.push(user.jtype);
idArray.push(user.id);
});
container.innerHTML = "";
for (let i = 0; i <= 3; i++) {
let clone = row.cloneNode(true);
container.appendChild(clone);
container.firstChild.innerHTML = "";
jobtitle.innerHTML = data[i].title;
jbtype.innerHTML= typeArray[i];
jbaddress.innerHTML= addressArray[i];
sessionStorage.setItem('jobid',idArray[i]);
}
}
The issue I can see is , since the key is always same , it is overriding the value of the same key.
You can instead do something like
sessionStorage.setItem("jobid-"+i,idArray[i]);
This should solve the problem for sure.
It returns the last value because you are using the same key to store each value. Try using a different key for each or alternately, create an array of ids using map function and store the array in session with the key 'jobid'.
You can serialize and store it in session as follows:
sessionStorage.setItem('jobid', JSON.stringify(idArray));
To read the same back out you can use code like
JSON.parse(sessionStorage.getItem('jobid'));

How to add an element to multi-dimensional JSON array if the element key is a variable

There is a JSON file with an array like
{
"general_array":[
{"key_1":["a","b","c"]}
]
}
I want to add an element to the array e.g.
{"key_2":["d","e","f"]}
but the value of new key I get from a variable e.g.
var newKey = 'key_2';
I'm trying to add the element to the existed array as following
// ... getting file content
// var jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
jsonObj.general_array.push({newKey:['d','e','f']});
var newJsonFileContent = JSON.stringify(jsonObj);
// and rewrite the file ...
// console.log(newJsonFileContent);
But in the file I get
{
"general_array":[
{"key_1":["a","b","c"]},
{"newKey":["d","e","f"]}
]
}
i.e. as the new element key I get the NAME of variable, but I need its VALUE
How to add the value?
UPDATED
The solution with [newKey] works in most of browsers, but it doesn't work in Internet Explorer 11
I need a solution to be working in IE11 too, so the question is still actual
You can use [newKey] to get the value of the variable as a key name:
var jsonFileContent = `
{
"general_array":[
{"key_1":["a","b","c"]}
]
}`;
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
var tempObj = {};
tempObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(tempObj);
var newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent);
To use the value of a variable as a JSON key, enclose it in square brackets, like so:
{[newKey]:['d','e','f']}
let jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
let jsonObj = JSON.parse(jsonFileContent);
let newKey = 'key_2';
jsonObj.general_array.push({[newKey]:['d','e','f']});
let newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent)
This is the computed property name syntax. It's a shorthand/syntax sugaring for someObject[someKey] = somevalue
Try changing this line:
jsonObj.general_array.push({newKey:['d','e','f']});
For this:
var newObj = {};
newObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(newObj);

How to get value stored in array object in javascript

I m storing values as object which i get dynamically, now i need to retrieve those values, its simple question but i didnt get the answer so i asked here.
for example:
/* Adding values dynamically into array of saveData. */
at first :
id = 1
gettext = 'Y'
text = 'Hello world'
at second :
id = 2
gettext = 'N'
text = 'JavaScript'
etc....
My code:
var saveData = {};
var objterm = {};
objterm["valueID"] = id;
objterm["valueGot"] = gettext;
objterm["text"] = text;
saveData[id] = objterm; // Saving values in array...
How can i retrive a value eg: say, saveData[1] -> gettext, text
// I tried the below to get value as
var obj = _.find(saveData, function(obj) { return obj.id == id }); // did nt get values
From the code you provided both saveData and objterm are simple objects, so if you wanted to retrieve specific data from some specific entry to saveData all you need to do is this:
saveData[id].valueGot
based on
objterm["valueID"] = id;
objterm["valueGot"] = gettext;
objterm["text"] = text;
It is working after adding http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js
For _.find & _.findWhere method.
var saveData = {};
var objterm = {};
objterm["valueID"] = 1;
objterm["valueGot"] = 'Y';
objterm["text"] = 'javascript';
saveData[1] = objterm;
var obj = _.find(saveData, function(obj) { return obj.valueID == 1 });
var obj2 = _.findWhere(saveData, {valueGot: 'Y' });
console.log(obj)
console.log(obj2)
https://jsfiddle.net/anil826/7ay25qwu/

How to stock array with localStorage (Chrome Extension)?

I tried to stock an array in localStorage but then I read it was impossible. So I tried that:
array = {};
array.name = $('[name="name"]').val();
array.username = $('[name="username"]').val();
array.password = $('[name="password"]').val();
alert(localStorage['accounts']);
local = JSON.parse(localStorage['accounts']);
localu = local.push(array);
alert(JSON.stringify(localu));
In fact the scripts stops at the first alert which returns '[]' (I previously put that value to check the result).
Why isn't my script working?
JavaScript, {} is an Object. [] is an Array.
var array = [] and var array = new Array() do the same thing.
An array is an ordered container of stuff, each value has an index not a key.
An object is a named container of stuff, each "stuff" has a key.
Your array is definitely an object.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
alert(localStorage['accounts']);
// > undefined OR the value
local = JSON.parse(localStorage['accounts']);
// local contains a parsed version of localStorage['accounts']
localu = local.push(array);
// localu = 0 (push returns the length i think?)
alert(JSON.stringify(localu));
Try the following. I've not tested it, but might work.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
if (localStorage['accounts'] == undefined) { // fixed
// does the key exist? No so create something to get us started
localu = { accounts: [] };
} else {
// the key exists! lets parse it
localu = JSON.parse(localStorage['accounts']);
}
// add the new "data" to the list
localu.accounts.push(data);
// save the results (we have to stringify it)
localStorage['accounts'] = JSON.stringify(localu);

Categories

Resources