how to add a object to an object - javascript

I am unable to add a object to object.
i am creating a object with two 2 properties
i want to assign this object to another object
$scope.urlMappings = {};
$scope.Mapping = function() {
var newUrlMappingField = {};
newUrlMappingField.Url1 = '';
newUrlMappingField.Url2 = '';
$scope.urlMappings.push(newUrlMappingField);
and wat key would i need to use to call ng-repeat in html file ? i m using mapping in urlMappings
I am unable to add a object to object.
i am creating a object with two 2 properties
i want to assign this object to another object
and wat key would i need to use to call ng-repeat in html file ? i m using mapping in urlMappings

push() method is used to add items to an array, not an object.
To add items to an object you can use the bracket notation to set the property of the object and assign the new object to it.
$scope.urlMappings = {};
$scope.Mapping = function() {
var newUrlMappingField = {};
newUrlMappingField.Url1 = '';
newUrlMappingField.Url2 = '';
$scope.urlMappings["mapping"] = newUrlMappingField;
}
For the second question, as far as i understand
<div ng-repeat="(key, value) in urlMappings">
<div>{{key}}: {{value.Url1}} {{value.Url2}}</div>
</div>

Related

Is it necessary to create nested jSON objects before using it?

I think I've seen how to create a JSON object without first preparing it. This is how i prepare it:
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now I think I can insert a value like: obj.0.type = "type0"; But I'd like to create it while using it: obj['0']['type'] = "Type0";.
Is it possible, or do I need to prepare it? I'd like to create it "on the fly"!
EDIT
I'd like to create JS object "On the fly".
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now i think i can insert value like: obj.0.type = "type0";
I guess you mean "assign" a value, not "insert". Anyway, no, you can't, at least not this way, because obj.0 is invalid syntax.
But I'd like to create it while using it: obj['0']['type'] = "Type0";
That's fine. But you need to understand you are overwriting the existing value of obj[0][type], which is an empty object ({}), with the string Type0. To put it another way, there is no requirement to provide an initialized value for a property such as type in order to assign to it. So the following would have worked equally well:
obj = {
0:{},
1:{},
2:{}
};
Now let's consider your second case:
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
Think closely about what is happening. You are creating an empty obj. You can assign to any property on that object, without initializing that property. That is why the assignment to obj.test works. Then in your second assignment, you are attempting to set the test property of obj.test, which you just set to the string "test". Actually, this will work--because strings are objects that you can set properties on. But that's probably not what you want to do. You probably mean to say the previous, string value of obj.test is to be replaced by an object with its own property "test". To do that, you could either say
obj.test = { test: "test" };
Or
obj.test = {};
obj.test.test = "test";
You are creating a plain object in JavaScript and you need to define any internal attribute before using it.
So if you want to set to "Type0" an attribute type, inside an attribute 0 of an object obj, you cannot simply:
obj['0']['type'] = "Type0";
You get a "reference error". You need to initialize the object before using it:
var obj = {
0: {
type: ""
}
};
obj['0']['type'] = "Type0";
console.log(obj['0']['type']);
You could create your own function that takes key as string and value and creates and returns nested object. I used . as separator for object keys.
function create(key, value) {
var obj = {};
var ar = key.split('.');
ar.reduce(function(a, b, i) {
return (i != (ar.length - 1)) ? a[b] = {} : a[b] = value
}, obj)
return obj;
}
console.log(create('0.type', 'type0'))
console.log(create('lorem.ipsum.123', 'someValue'))
Is it necessary to create nested objects before using it?
Yes it is, at least the parent object must exist.
Example:
var object = {};
// need to assign object[0]['prop'] = 42;
create the first property with default
object[0] = object[0] || {};
then assign value
object[0]['prop'] = 42;
var object = {};
object[0] = object[0] || {};
object[0]['prop'] = 42;
console.log(object);
Create object with property names as array
function setValue(object, keys, value) {
var last = keys.pop();
keys.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var object = {};
setValue(object, [0, 'prop'], 42);
console.log(object);

Alternative to variable keys in Meteor

How can I use a variable value as an object key?
For example, when adding an object dynamically to a Collection. When I to do it like this:
addToDB(type, account) {
Accounts.insert({type: account});
};
it doesn't work as the key can't be a variable here.
JavaScript object literal don't support dynamic keys.
Instead you can achieve the goal using :
var obj = {};
var key = "some key";
obj[key] = "test";
In your case:
addToDB(type, account) {
var obj = {};
obj[type] = account;
Accounts.insert(obj);
};
More details here:
Creating object with dynamic keys

create object within object Javascript

My Code :
for( var i in zones) {
var latlons1 = new google.maps.LatLng(zones[i].b.cen_x, zones[i].b.cen_y);
var latlons2 = new google.maps.LatLng(zones[i].b.max_x, zones[i].b.max_y);
var latlons3 = new google.maps.LatLng(zones[i].b.min_x, zones[i].b.min_y);
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} } //here object creation
console.log(obj1);
}
what i am doing wrong? consol log error shows at object create.
When creating an object literal in JavaScript the key and value are separated by a colon (:). Also note that if you want to use dynamic keys then you'll need to use the square bracket notation for setting and accessing those properties. So this:
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} }
should become:
obj1 = {};
obj1[zones[i].n] = {
1: latlons1,
2: latlons2,
3: latlons3
};
If you're confused as to why you have to do it this way it's because the keys aren't evaluated. While you meant that the key should be the value that's referenced by zones[i].n, JavaScript interprets it as the key should be the string literal "zones[i].n", which obviously isn't what you want.
To use an object within an object,
//An object within an object
var NestedObject=new Object();
NestedObject.one={
sad:{
d:"Add"
}
}
I solved this using experimental coding within Codecademy.com;
Thanks for letting me share my answer!

Dynamic Javascript Object creation

How can I make php array into Javascript object code?.
You can try this. This is how you dynamically name object properties and object values. I am assuming you want to build this dynamically where the property names are coming from a source. All you have to do is loop through the values
var treeData = {};
Loop Here
var nameProperty = "propertyName";
var nameValue = "propertyValue";
var childProperty = "child";
var childValue = {};
Try This.
http://jsfiddle.net/zKdMa/1/

Change key in js associative array

If I have:
var myArray = new Array();
myArray['hello'] = value;
How can I change the key 'hello' to something else?
Something like this would work.
var from = 'hello',
to = 'world',
i, value = myArray[from];
for( i in myArray )
if( i == from ) myArray.splice( i, 1 );
myArray[to] = value;
But is there a native function or a better way to do it?
edit:
Due to the lack of associative arrays in js, what I want to do modify the property name of an object as efficiently as possible.
In JavaScript there is no such thing as associative Array. Objects can be used instead:
var myHash = new Object();
or
var myHash = {};
replace can be done like this:
myHash["from"] = "value";
myHash["to"] = myHash["from"];
delete myHash["from"];
but the preferred way to write it:
myHash.from = "value";
myHash.to = myHash.from;
delete myHash.from;
You can't really "change" the property name, but you can always assign a property value to a new name, and then delete the original one.
myArray['world'] = myArray.hello;
delete myArray.hello;
Also, you're working with an Array instance but using it as a simple object; everything you're doing would work just as well with:
var myArray = {};
The "splice()" you're attempting in the code posted won't work, because it's only for the actual integer-indexed array properties, and not the named properties.
That "delete" doesn't really delete a property really doesn't matter. The "undefined" value is what you get when you check an object for a property and there's no such property.

Categories

Resources