I'm trying to dynamically populate a HashMap in jQuery, and am following this example: https://stackoverflow.com/a/4247012/1005607 Orig Question: How to create a simple map using JavaScript/JQuery
I need to add a hash entry where the key comes from an array item, and the value is a variable. But I'm getting an error. What's wrong? This should be equivalent to populating "item2" -> 2 in the HashMap. I would be able to get 2 by invoking laneMap.get("item2").
var laneMap = {};
var eventIDs = [];
eventIDs.push('item1');
eventIDs.push('item2');
var currlane = 2;
laneMap.push({eventIDs[1] : currlane });
You can't add key/value pair using push. There are two ways of doing it
Using dot notation:
obj.key3 = "value3";
Using square bracket notation:
obj["key3"] = "value3";
var laneMap = {};
var eventIDs = [];
eventIDs.push('item1');
eventIDs.push('item2');
var currlane = 2;
laneMap.key = currlane-1;
laneMap[eventIDs[1]] = currlane ;
console.log(laneMap);
P.S.- You can't use [] in dot notation
You can only use .push with an array. Here's how to assign a dynamic object property:
laneMap[eventIDs[1]] = currlane;
Related
I want to create an array of JSON object without a key.How can this is achieved ..??
for example [{8,0,2}, {20,0,2}].
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})
it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]
You example uses a new feature of ECMAScript 6 that is the shorthand syntax for initialising object properties. This line in your example:
data.push({hh,mm,qty});
is equivalent to this verbose one:
data.push({hh: hh, mm: mm, qty: qty});
An object in JavaScript will always have keys and values. There is no way to save just values in a plain object. However, there are two other solutions.
One is using an array:
data.push([hh, mm, qty]);
Note the square brackets substituting the curly ones. This will obviously push an array of three values onto the data array. When retrieving the values, you can just refer to their index, as an array's items will always retain their indices:
var data2 = [hh, mm, qty];
var hh2 = data2[0];
var mm2 = data2[1];
var qty2 = data2[2];
Another way of just "saving the values" is using a set, though the construction of a Set object will still require passing it an array:
data.push(new Set([hh, mm, qty]));
Accessing the data is less straightforward in this case, as the set will typically only let you iterate it. Unlike similar data structures in other languages, a JavaScript set will retain the order of inserted values. It can therefore be safely converted into an array:
var mySet = new Set([hh, mm, qty]);
var data3 = Array.from(mySet);
var hh3 = data3[0];
var mm3 = data3[1];
var qty3 = data3[2];
You can read more about sets here.
You can wrap it over another JSON object with a key I assume you want a JSON object.
Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.
I had a similar problem for one of my scenario. Then I realised
A top level JSON can't exist without a key!
Consider this example, you have another KV pair in JSON and also this array.
{
"somekey" : "somevalue",
[ {8,0,2}, {20,0,2} ]
}
You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(
I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:
{
"my array" : [ {8,0,2}, {20,0,2} ]
}
Without a key value pair, the object was not created. That's why its adding a key using the variable name
Look at this error. Its invalid code
var a = [{8,0,2}, {20,0,2}];
console.log(a)
You could push to an array instead of an object
var data = [];
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push([hh,mm,qty])
console.log(data)
You can't.
Object Literal Property Value Shorthands allow you to create an object where the property names are inferred from the variable names you use to pass the data into.
If you don't have variable names, then there is nothing for the JS engine to use to figure out what the property names should be.
Consider using a function instead.
console.log([time(8,0,2), time(20,0,2)]);
function time (hh, mm, qty) {
return {hh, mm, qty};
}
The result you get at the end makes sense. By doing {hh,mm,qty} you are effectively saying "Use the variable name as the key and its value as the value". It might help us more if you provide an example of how you intend to use the result and access the variables i.e. the shape of the object you want in the end.
That being said, there are a couple alternatives:
Using values as the keys
If you really wanted your object to look similar to {8,0,2} you could use those values as the keys (all keys get converted to strings anyways) so you could do the following:
var example1 = {8:undefined,0:undefined,2:undefined};
var example2 = {8:null,0:null,2:null};
var keys = [];
for(var name in example1) {
keys.push(name);
}
// keys = ["8","0","2"];
var otherKeys = Object.keys(example2);
// otherKeys = ["8","0","2"];
Setting the keys dynamically
var hh = 9;
var mm = 8;
var qty = 2;
var obj = {};
obj[hh] = null;
obj[mm] = null;
obj[qty] = null;
//obj = {9:null,8:null,2:null};
I'm not certain if this solves your problem or answers your question entirely but it might give you some more insight into what is happening and why. The above examples are a common way to create a quick lookup versus a dictionary with would have values in place of null or undefined.
I have an object of values and I am trying to populate two arrays with the keys and values from the object.
My Object:
obj = {19455746: 7476, 22489710: 473}
Loop attempting to append data:
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push[i];
sensorDataArray.push[obj[i]];
}
At the moment the two arrays are printing out as empty. My expected outout would be something like:
sensorNameArray = [19455746, 22489710];
sensorDataArray = [7476, 473];
push is a function, not an array, it uses parenthesis not brackets :
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
The syntax push[] doesn't invoke the function, it tries to access a property of the function object. It doesn't throw an error because in Javascript, functions ARE objects and this syntax is technically valid.
So, just fix the syntax to push() in order to actually invoke the function.
You are using square braces []
but array.push() is a function so use circle braces instead
Try the following code
obj = {19455746: 7476, 22489710: 473};
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
This is working and tested.
A different syntax (more elegant IMO) :
var sensorNameArray = Object.keys(obj)
var sensorDataArray = Object.values(obj)
or :
var sensorDataArray = sensorNameArray.map( key => obj[key] )
Best way to deal with JSON is use lodash or underscore.
_.key() and _.value are functions for your requirement.
Eg.:
obj = {19455746: 7476, 22489710: 473};
sensorNameArray = _.keys(obj);
sensorDataArray = _.values(obj);
If you want to proceed in your way, then you can use parenthesis as push inbuilt function of Javascript for inserting element into array.
Correct is:
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
So, I need to convert a json object like this {"0":"sometext","1":"someothertext"} into a javascript array with the index matching the integer and the data at the index the string. I tried using JSON.parse() but it didn't work since this happens.
var json = '{"0":"sometext","1":"someothertext"}';
var obj = JSON.parse(json);
//Then when I would want to assign a part of the object to a variable this gives me an error
var somevar = obj.0;
You can simply iterate over every property in the object and assign them as values in the array:
var obj = {"0":"sometext","1":"someothertext"};
var arr = [];
Object.keys(obj).forEach(function (key) {
arr[key] = obj[key]
});
Use bracket notation:
Change
var somevar = obj.0;
to
var somevar = obj[0];
I'm trying to understand how to add a value into my array. It is multidimensional:
var eventcontent = {
'2015-05-02' : [{'title':'somethingtitle1','content':'somethingcontent1','something':'something1'},{'title':'somethingtitle2','content':'somethingcontent2','something':'something2'}],
'2015-05-07' : [{'title':'somethingtitle7','content':'somethingcontent7','something':'something7'}],
}
How can I achieve adding the following data into the '2015-05-02'?
{'title':'somethingtitle3','content':'somethingcontent3','something':'something3'}
thanks for your help
eventcontent is object. Firstly you have to gain access to array stored under 2015-05-02 key. 2015-05-02 is not valid property identifier so you can't access it via
var array = eventcontent.2015-05-02 // SyntaxError
instead you have to use bracket notation
var array = eventcontent['2015-05-02'];
then you can for example push your data to the array
var data = {'title':'somethingtitle3','content':'somethingcontent3','something':'something3'};
var array = eventcontent['2015-05-02'];
array.push(data);
Edit:
Probably you should also check if array actually exist so your code becomes:
var data = {'title':'somethingtitle3','content':'somethingcontent3','something':'something3'};
var array = eventcontent['2015-05-02'];
if (array === undefined) // check if it is undefined and if so...
array = eventcontent['2015-05-02'] = []; // make empty array and assign it to eventcontent under '2015-05-02' key
}
array.push(data);
I am using an array as defined below
cat_id = Object { 2="text", 3="TKL1", -1="Select an Attribute"}.
when i am trying to retrieve the length of "cat_id" as
var l = cat_id.length;
its showing the length as "undefined".
But, I am unable to get the length of "cat_id". I am unable to use replace(), indexOf() and split() functions.
for example:
var index = cat_attr.indexOf(",")
Its showing error as below:
TypeError: cat_attr.indexOf is not a function
This isn't array, this is Object. Array defined in this way: [1,2,3]. If you want retrieve the "length" of object you can do this in this way:
var students = {job:92, adam:67,sara:83};
var studentNames = Object.keys(students);
var studentsLength = studentNames.length;
If you want split object to array you can do this in this way:
var students = {jon:92, adam:67,sara:83};
var studentNames = Object.keys(students);
var studentArray = studentNames.map(function(name){
var student = {};
student.name = name;
student.grade = students[name];
return (student);
}); // [{name:jon,grade:92},{name:adam,grade:67},{name:sara,grade:83}]
cat_id variable you defined as not an array, it is a javascript object. That is why it is not behaving like array! [] is the array notation. Use array notation [] instead of {} object notation you have used.
Your problem is wrong type and wrong syntax.
In your question your cat_id is an Object, not string or array. So you can not call length() or indexOf() funtion.
Moreover, you typed wrong syntax, it should be:
var cat_id = { 2: 'text', 3: 'TKL1', -1: 'Select an Attribute'}.
Here is how to retrieve property count (size and/or length)
size_obj = Object.keys(my_object).length;
As in
size_cat_id = Object.keys(cat_id).length;