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);
}
Related
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 };
});
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 ]
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;
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"},
...
];
This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).