How to get value stored in array object in javascript - 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/

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 can I store key in jQuery

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

Why Is My JavaScript Object Throwing An Undefined Error?

I am getting this error in my console:
Uncaught TypeError: Cannot read property 'kbsrc' of undefined
I get this error because I think there may be something wrong with the way I created my JavaScript Object. I have never created an object that is as multidimensional as this one so I am probably screwing up the syntax somewhere. I generate the objects in the mark-up file here:
var kb_work = {}
kb_work['2014'] = {};
kb_work['2014']['kbid'] = ["51","47"];
kb_work['2014']['kbsrc'] = ["images\/images-4.jpeg","images\/imgres-3.jpeg"];
kb_work['2014']['kbtitle'] = ["shalom","Test 6"];
kb_work['2014']['kbmedium'] = ["2x2","Oil"];
kb_work['2014']['kbsize'] = ["2x2","2x6"];
kb_work['2014']['kbdate'] = ["2014","2014"];
kb_work['2013'] = {};
kb_work['2013']['kbid'] = ["55","54","53","52","50"];
kb_work['2013']['kbsrc'] = ["images\/imgres-4.jpeg","images\/imgres-3.jpeg","images\/imgres-1.jpeg","images\/images.jpeg","images\/images-3.jpeg"];
kb_work['2013']['kbtitle'] = ["totally","heheh","Howdy","tickle","hi"];
kb_work['2013']['kbmedium'] = ["oil","oil","2x2","o","oil"];
kb_work['2013']['kbsize'] = ["2x2","2x2","2x2","2x2","2x1"];
kb_work['2013']['kbdate'] = ["2013","2013","2013","2013","2013"];
kb_work['2012'] = {};
kb_work['2012']['kbid'] = ["49"];
kb_work['2012']['kbsrc'] = ["images\/images-2.jpeg"];
kb_work['2012']['kbtitle'] = ["chicked"];
kb_work['2012']['kbmedium'] = ["oil"];
kb_work['2012']['kbsize'] = ["3x4"];
kb_work['2012']['kbdate'] = ["2012"];
Each of these arrays have only one value right now, but will grow as the user adds work. Following this I link to a file, which contains this function (I commented on the specific line) that the TypeError refers to:
function changeGal(gallery_year) {
$("#gallery-control-bar").fadeOut(t);
$("#gallery-image").fadeOut(t);
$("#info").fadeOut(t);
$("#gallery-viewer").fadeOut(t);
//this is where the script chokes up referring to "currentImg" which is 0 and refers to the first value in the array "['2014']['kbsrc']".
$("#gallery-image").html("<img src='" + kb_work[gallery_year]['kbsrc'][currentImg] + "'>");
$("#gallery-title").html(kb_work[gallery_year]['kbtitle'][currentImg]);
$("#gallery-medium").html(kb_work[gallery_year]['kbmedium'][currentImg]);
$("#gallery-size").html(kb_work[gallery_year]['kbsize'][currentImg]);
$("#gallery-date").html(kb_work[gallery_year]['kbdate'][currentImg]);
$("#gallery-control-bar").delay(t + d).fadeIn(t);
$("#gallery-image").delay(t + d).fadeIn(t);
$("#info").delay(t + d).fadeIn(t);
var userCurrent = currentImg + 1;
var userTotal = kb_work[gallery_year][0].length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
}
Any thoughts to why it cannot reference the value?
I think you need
$("#gallery-image").html("<img src='" + kb_work[gallery_year][gallery_year + '.kbsrc'][currentImg] + "'>");
because it looks like gallery_year is a year value like 2013, but the key is a concatenation string value like 2013.kbsrc
There is another problem with your structure because kb_work[year] should be an obeject not an array, again the second level of keys need not have the year again.
So the structure can be updated to
var kb_work = {}
kb_work['2014'] = {};
kb_work['2014']['kbid'] = ["46"];
kb_work['2014']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2014']['kbtitle'] = ["Test 5"];
kb_work['2014']['kbmedium'] = ["Oil"];
kb_work['2014']['kbsize'] = ["2x5"];
kb_work['2014']['kbdate'] = ["2014"];
kb_work['2013'] = {};
kb_work['2013']['kbid'] = ["44"];
kb_work['2013']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2013']['kbtitle'] = ["Test 3"];
kb_work['2013']['kbmedium'] = ["Oil"];
kb_work['2013']['kbsize'] = ["2x1"];
kb_work['2013']['kbdate'] = ["2013"];
kb_work['2012'] = {};
kb_work['2012']['kbid'] = ["45"];
kb_work['2012']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2012']['kbtitle'] = ["Test 4"];
kb_work['2012']['kbmedium'] = ["Oil"];
kb_work['2012']['kbsize'] = ["2x3"];
kb_work['2012']['kbdate'] = ["2012"];
then to access it
kb_work[gallery_year]['kbsrc'][currentImg]
Your nesting shows that you think this works differently to how it actually works...
var kb_work = {}
kb_work['2014'] = new Array();
kb_work['2014.kbid'] = ["46"];
Actually results in an object like this: {"2014":[],"2014.kbid":["46"]}
I believe you want this:
var kb_work = {
'2014': [
{ 'kbid': ["46"] }
]
};
Which results in an object like this: {"2014":[{"kbid":["46"]}]}
Now you can access:
kb_work['2014'][0].kbid[0] // 46
And you can pass in the year as a variable containing the string and the 0s can be a variable containing the index.
You can add multiple lines like this:
var kb_work = {
'2014': [
{ 'kbid': ["46"] },
{ 'kbid': ["62"] },
{ 'kbid': ["90"] }
]
};

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

Categories

Resources