How to create object of array in Javascript - 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 ]

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

JavaScript Two dimensional Array

I am creating javascript two dimensional array
code is :
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
Output Is:
[undefined, [] left 140 paId "1" top 10
What is problem in It Any help Should be appreciated.
The problem is in the display method of your arrays. The information is there, but both alert and console.log will not show it to you because it is expected that the only interesting properties of arrays are the ones with numeric indexes.
In JavaScript, unlike PHP, objects are used as maps/associative arrays.
First to check that your information is actually there:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
Now to make make the display methods work you can go about multiple ways, but the best one is to use objects instead:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
Iterating over properties of objects is quite easy:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
Add a hasOwnProperty check if your object doesn't inherit from null (var obj = {} needs it, unlike var obj = Object.create(null))
you're storing values with a key string and its wrong because you declared your field_arr as a numerical array (well there's no such thing as associative array in javascript i think).
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
You need to create an object to store in values as if they are associated with string keys. But literally they are object properties
redeclare it like this
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
EDIT:
but to conform to you current code you can access your indexes using strings by accessing it like a property of an object. (Thanks to Tibos)
var field_arr=[];
...
...
field_arr[Id].paId = paId;

Can Javascript objects be accessed like arrays?

Assuming an object is initialized as following:
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
Can I retrieve key values like this?
var retrKey1 = myObj[0];
var retrKey2 = myObj[1];
var retrKey3 = myObj[2];
...
The issue I am trying to solve is that I need to pick random key values from this object. Generating a random number is not an issue, but:
How can I retrieve the number of keys in the object/map?
Can I retrieve the key values using a integer index like in arrays?
If not, what are my options?
The Object.keys method returns an array of object properties. You can index the array with numbers then.
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
var keys = Object.keys(myObj);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
No, because there's no ordering among property keys. If you want ordered keys, you need to work with an array.
You could define a structure like this :
var myObj = [
{key:"key1", val:"val1"},
...
];

insert an array with a custom name into a two dimensional array - javascript

I have a two dimensional array which I created like this
var books = new Array(); // create an Array
var book1 = new Array();
book1.push("1");
book1.push("adfgsdg");
book1.push("dfgsdfg");
book1.push("dfgds");
book1.push("44.95");
book1.push("dfgsd");
book1.push("dfgsdg");
books.push(book1);
var book2 = new Array();
book2.push("2");
book2.push("gdhff");
book2.push("fghfd");
book2.push("fghdf");
book2.push("44.95");
book2.push("2000-12-16");
book2.push("fghfghd");
books.push(book2);
can you tell me how to dynamically create a new book3, book4.... array and push into the books array.
Just use an object:
var books = {book1: ['book1 title', 'book1 - title2']};
books['book2'] = ['book2 titles'];
books.book3 = [];//works, too
books.book3.push('foobar');
If you insist on having variables that reference a particular array, that's very easily done:
var book2 = books.book2;//arrays are objects, so:
book2.push('A second title');
console.log(books.book2[1]);//logs "A second title"
Easy-peasy. on the dynamic names front, just a quick example:
books['book' + someVar] = [];
Works just fine.
As #raghaw pointed out, perhaps you could do with some explaining:
JavaScript doesn't really support associative arrays as such, instead objects are used (even Array's are just "pimped" objects, but that's a different matter)
You can create a new instance of any object by calling the construct (new X(), like you did), but in case of native object types (like Array and Object), that's not to be recommended (new Array(10); and new Array('10') behave differently, for example).
In those cases the literal notation is to be preferred:
var wrong = new Object();//not "wrong", but impredictable
var better = {};//or new [whateverTypeOfObject]();
//ditto for arrays:
var dangerous = new Array();
var safe = [];
To assign an object/array with a certain set of values already there, simply fill them in:
var myObject = {key: "value",
theValue: {can: 'be',
anything: ["even", "another", "object"]}
};
The data can be accessed both by using the dot-notation or the bracket notation:
console.log(myObject.theValue['can']);//be
//===
console.log(myObject.theValue.can);//be
//===
console.log(myObject["theValue"]["can"]);//be
If you're using variables as keys, you'll have to use the bracket notation. If you feel like you need more info check out MDN, spend some time on that site - it's a good reference on JS
First of all I think that the answer by Elias is very good. However, if you are not in the mood of going OO, just create books 3 and 4 as raghavv told in the comment, then push them all in the books array
books.push(books1);
books.push(books2);
books.push(books3);
books.push(books4);
The result of it will be actually something like
var books[
books1[value1, value2, value3],
books2[value1, value2, value3],
books3[value1, value2, value3],
books4[value1, value2, value3]
];

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

Categories