Changing my simple JS Array to have key/values instead - javascript

Im currently using jQuery to build an Array like this:
var arr = new Array();
$('#some-form .some-input').each(function() {
arr.push($(this).val());
});
which builds something like:
arr[0] = 'bar'
arr[1] = 'foo'
Now I want a data structure (a 'map'? a JSON array?) to do get something like this:
{ 'key1' : 'foo'
'key2' : 'bar' }
because I am now going to store multiple 'things' from $('#some-form .some-input').
In C, I think this could be a linked list because you don't know how big the data structure will be in advance so you wouldn't use an array. However, I AM using an array here which might not be the best idea? What's sort of structure do I need?
Many thanks.

With javascript you can dynamically add properties to an object, so you can do something like this:
var arr = {};
$('#some-form .some-input').each(function() {
var $this = $(this);
arr[$this.attr('id')] = $this.val();
});
And you can access them with arr.key1; // foo
Edit: as the comments below note, you can also access the values using the [] notation, like arr['key2'] // bar (thanks for reminding me :))

Related

push Object in array in $.each

Maybe I'm just blind, but I'm struggling for a good amount of time now:
I have a small piece of JS-Code here:
var linkInput = $('#Link input.gwt-TextBox').val();
var parentRow = $('#Link').parent().parent();
var links = linkInput.split("|");
// hide text-input
$(parentRow).hide();
// get rid of empty elements
links = links.filter(Boolean);
var aSites = [];
var oSite = {};
$(links).each(function (k, v) {
splits = v.split(".");
domainName = splits[1];
oSite.name = domainName;
oSite.url = v;
aSites.push(oSite);
});
console.log(aSites);
To specify: Get the value of an input-field, hide the row afterwards and save all the values in an object, which is then pushed into an array.
The parameter, taken from the console-tab of google Chrome:
var links = ["www.myshop1.de/article/1021581", "https://www.myshop2.de/article/1021581"] [type: object]
I thought, I iterate through all elements of this object (in that case 2 times), push the values into an object and the object into an array, to have access to all of them afterwards.
At some point however, I seem to override my former values, since my output looks like this:
0: {name: "myshop1", url: "https://www.myshop1.de/1021581"}
1: {name: "myshop2", url: "https://www.myshop2.de/1021581"}
length: 2
__proto__: Array(0)
Where is my mistake here? Is there a smarter way to realize this?
On a sidenote:
I tried to use only an array (without adding an object), but it seems like I
can't use an associative key like this:
var myKey = "foo";
var myValue = "bar";
myArray[myKey] = myValue
You should move this:
var oSite = {};
...inside the each callback below it, because you need a new object in each iteration.
Otherwise you are mutating the same object again and again, pushing the same object repeatedly to the aSites array, which ends up with multiple references to the same object.
Not related, but you can use $.map to create your array (or vanilla JS links.map()):
var aSites = $.map(links, function(v) {
return { name: v.split(".")[1], url: v };
});

How to create object of array in Javascript

I want to create the object of list that looks like this:
myObj = {"foo":[1,2,3,4],
"bar":[3,5,7,8]}
I tried this but failed
var myObj = new Object();
myObj["foo"].push(1)
myObj["foo"].push(2)
#...etc
What's the right way to do it?
You need to create the array first
myObj["foo"] = []
then call your push method
It depends, are you trying to reassign the myObj attribute foo with a completely new array? Or are you trying to append to the already existing array?
In the former case:
myObj.foo = [1,5,6,4] // new array
And in the latter:
myObj.foo.concat(/*new numbers*/)
The {} notation is commonly used.
var myObj = {};
myObj.foo = [];
myObj.bar = [];
Later you can manipulate the arrays.
myObj.bar.push('elem1');
myObj.bar.pop();
// ...
First you should declare the properties of the object as array in order not to get some unpleasent situations.So you can use new Object to create an object like this.
var myObj=new Object;
and define properties as empty arrays
myobj.prop1=[];
myObj.prop2=[];
then you can push whatever you want into prop1 or prop2 by simply reaching them inside the object as
myObj.prop1.push(someData)
OR
You can use a better way to declare this object like below
var myObj={
prop1:[],
prop2:[]
}
And again you can push whatever you like into them as i told above
as myObj.prop1.push(data)
Try first declare your object, so your second line goes first
var myObj = new Object();
then you fill your object with data
myObj = {"foo":[1,2,3,4],"bar":[3,5,7,8]}
then the rest of your code should work fine
myObj["foo"].push(1)
myObj["foo"].push(2)
result [ 1, 2, 3, 4, 1, 2 ]

How I can build this json object with javascript code?

{
"ma.addEvents":{
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
I don't understand how I can create object like "ma.addEvent"
the "dot" is a problem here.
Try this
var x = {
"ma.addEvents":{
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
If you want to access, you have to use [] notation (. notation won't work, because of dots in keys) like
console.log(x["ma.addEvents"]["ma.id"])
You might want to use a square bracket notation:
var yourObject = {};
yourObject['ma.addEvents'] = {};
...and so on. Print the ma.addEvents attribute using
console.log(yourObject['ma.addEvents'])
You can use this:
var json_string = "{\"ma\.addEvents\":{\"ma\.id\":\"my-id\",\"ma\.eventIds\":[\"eventID1\",\"eventID2\"]}}";
The code above, when parsed to json (JSON.parse), will retrieve the same object that appears on your question.
Hope this helps,
Regards,
Marcelo
var obj = {
"ma.addEvents": {
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
Depends on what part you would like to add dynamically.
var obj = {};
obj["ma.addEvents"] = {
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
};
obj["ma.addEvents"]["ma.eventIds"].push("someotherEvent");
Please take a look at the documentation for accessors.
ma must be defined before you create ma.addEvents etc. The syntax might look like this:
// `ma` is an object
var ma = {
// It contains an object called `addEvents`
addEvents: {
// Which contains a string `id` and an array `eventIds`
id: "my-id",
eventIds: [
"eventId1",
"eventId2"
]
}
}
To create a blank object in ma, you could use the 'dot' syntax:
ma.newObject = {};
or square bracket notation:
ma["newObject"] = {};
I'm not entirely sure what your question is, are you looking to parse that JSON or to learn Javascript object syntax?

add anonymous object to an object

I know to add a named object to an existing JavaScript object you do this:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for() statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
UPDATE:
I want the end result to look like this:
var json = [{name:'a'}{name:'b'}];
What you have there is not strictly a JSON object. You're using JS object literals rather.
You can do this:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSON representation of above will look like:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
// invalid, will throw error
jsObj = { : 'a'};
Try an array that you push an item on to using
myArrayVar.push(value);
or
myArrayVar[myArrayVar.length] = value;
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
for (var k in obj)
will set "k" equal to each of the names of properties in "obj" in turn.
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
http://www.json.org/
What you are describing is an array of objects.
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
for(var i in j) {
alert(j[i].name);
}

Efficient syntax for populating a javascript associative array

I have an autocomplete text box that users can type an item code into and need to find out what the id number of that item code is in javascript.
An associative array is the way I would imagine it should be done, but the following seems a little long winded and I'm hoping someone has a better way to do it or shorthand of what I have below:
var itemIds = new Array();
itemIds["item1"] = 15;
itemIds["item2"] = 40;
itemIds["item3"] = 72;
...
function getItemId(code){
return itemIds[code];
}
What you're doing isn't an array - it's an object (objects in JavaScript are the equivalent-ish of associative arrays in PHP).
You can use JavaScript object literal syntax:
var itemIds = {
item1: 15,
item2: 40,
item3: 72
};
JavaScript object members can be accessed via dot notation or array subscript, like so:
itemIds.item1;
itemIds['item1'];
You'll need to use the second option if you've got the member name as a string.
Try using Object Literal notation to specify your lookup like this:
var itemIds = {
"item1" : 15,
"item2" : 40
...
};
Access should still work like this:
var item1Value = itemIds["item1"];

Categories