How can I store key in jQuery - javascript

Here is My code :
function addtocart(id,price) {
var qty = $("#txt_qty" + id).val();
var qty1 = new Array();
if (qty == '' || qty == 0) {
alert('Please Enter Quantity');
$("#txt_qty" + id).focus();
return false;
}
if (qty != '' && type != '') {
proid.push(id);
var text = 'qty'+id+'='+qty;
var keyValuePair = text.replace(/ /g,'').split('=');
qty1.push([keyValuePair[0]] = [keyValuePair[1]]);
}
I need to store key in qty1 array,I have already value called qty
How can i dynamically store key in qty1 array
I am trying above attempt but not succeeded
Can anybody help me

If you got already data value for keyvaluepair[0] and keyvaluepair[1], then try use this :
var myObj = {}; // declare obj container
myObj[keyvaluepair[0]] = keyvaluepair[1]; // set key and value based on your variable
qty1.push(obj); // finally push obj into your qty1(array) variable
This is just an alternative, you can try use the solution provided by #Disha V.

Try this : You need to set value against specific key, see below code. Also define new map like belwo
var qty1 = new Object();//create new map and not array
qty1[keyValuePair[0]] = keyValuePair[1];
to read value again from map use below code
var value = qty1[keyValuePair[0]];

Associative array (name index) are treated as object in javascript/jquery. So you can use like this
var qty1= {"key1":"value1", "key2":"value2", "key3":"value3"};
var test = qty1.key1; // "value1" will be returned
Or you can use array like this but it will be converted in object as above
var qty1= [];
qty1["key1"] = "value1";
qty1["key2"] = "value2";
qty1["key3"] = "value3";
var test = qty1[0]; // qty1[0] will return undefined
var test2 = qty1.key1; // "value1" will be returned

Related

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);

javascript - How to get the value of variable as variable with window in an object

key = 'first_name';
// This key might be anyting else
// key = 'last_name';
// key = 'age';
value = 'Ali';
// This value might be anyting else
// value = 'Jones';
// value = '50';
I want to send the value of an object using ajax like this:
key_value = {first_name: 'Ali'};
however the first_name above might change each time, so I tried:
key_value = {key: value};
however I want the value of key which is first_name in this example so I tried to use window
key_value = {window['key']: value};
But it throwed an error:
SyntaxError: missing : after property id
How can I fix this? THANKS
You can try this:
var key_value = {};
key_value[key] = value;
Snippet Example:
var key = 'first_name';
var value = 'Ali';
var key_value = {};
key_value[key] = value;
console.log(key_value);
Why not make use of shorthand property assignment in the object:
var key = 'first_name';
var value = 'abc';
var key_value = {[key]:value};
console.log(key_value);
var jsonVariable = {};
var key='first_name';
var value='Ali';
jsonVariable[key]=value;
Send jsonVariable through Ajax.

how to find nearest values both lower and upper in a javascript object?

I need to extract closest lower value and closest higher value in a javascript objet.
My logic is to iterate on the objet and put in a variable all values which are inferior than the value of my product (then do the same with the closest higher value and all values which are superior)
The value that I want to extract in that example is the date that is the first value of the object which is constructed like this : "object":[[val1, val2],[val1, val2]]
Do you think my logic is the good one, and can you see what's wrong with my code?
var datagrph = $.parseJSON('{"label":"Yo", "fromDate":"2015-06-05", "launchDate":"2016-08-15", "dateValues":[["2014-06-05",1723.76], ["2015-06-29",1523.76], ["2015-12-29",1023.76], ["2017-01-29",523.76], ["2017-02-22",1523.76], ["2017-03-29",523.76], ["2017-04-29",1523.76], ["2017-05-29",23.76], ["2017-06-21",523.76] ]}');
var productCour = datagrph.dateValues;
var launchDate = datagrph.launchDate;
var val1 = [0];
Object.keys(productCour).map(function(objectDate, index) {
var value = object[objectDate];
if (value <= launchDate) {
val1.push(value);
} else if (value > launchDate) {
value++;
}
return val1;
});
alert(val1);
Simply calculate the difference between the current date and launchDate, then set the values accordingly:
var datagrph = $.parseJSON('{"label":"Yo", "fromDate":"2015-06-05", "launchDate":"2016-08-15", "dateValues":[["2014-06-05",1723.76], ["2015-06-29",1523.76], ["2015-12-29",1023.76], ["2017-01-29",523.76], ["2017-02-22",1523.76], ["2017-03-29",523.76], ["2017-04-29",1523.76], ["2017-05-29",23.76], ["2017-06-21",523.76] ]}');
var productCour = datagrph.dateValues;
var launchDate = +new Date(datagrph.launchDate+" T00:00");
var before,after,diffmin,diffmax;
productCour.forEach(function(pair){
var current=+(new Date(pair[0]+"T00:00"));
var difference=launchDate-current;
if(difference>0){
//launchDate not reached
if(!diffmin || diffmin>difference){
//weve got a new before
before=pair[1];
diffmin=difference;
}
}else{
//launchDate already reached
if(!diffmax || diffmax<difference){
//weve got a new after
after=pair[1];
diffmax=difference;
}
}
});
before and after should now contain the nearest values.
before:1023.76
after: 523.76
http://jsbin.com/cozovecaha/edit?console

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