I try to do something like this:
var obj = {id: id, items: "asdf", items: "sdff", test: varTest};
BUT I need to add the two same named items called 'items' dynamically. Because it won't be always the same number of these elements. How can I add them to this object, without overwriting them itselfs?
Thank you very much.
PS: I know that this is probably not a good idea, but I use an API so I can't change this. I need to give them the same name.
You cannot use same key multiple times in an object. You can use array.
var obj = {id: id, items:["asdf", "sdff"], test: varTest};
This will be easy to access the elements having same semantics.
To add items use,
if (obj.hasOwnProperty(items)) {
obj.items.push(newVal);
} else {
obj.items = [newVal];
}
Related
So I need to edit a property of an object in javascript. It contains multiple of the same object name. I am fairly familiar with javascript. My object looks like this:
var object = {
Sub: {
name: "FirstSubName",
propertyToChange: "Keep me the same"
},
Sub: {
name: "SecondSubName",
propertyToChange: "Change me" //This is the property I need to change
}
}
I want to change the second property of the second "Sub" to "ChangedProperty". If I want to do it without using chronological order (like object.Sub[1].propertyToChange = "ChangedProperty", what would I do?
As Bergi said, you cannot have these two properties. What you can have is an array, like this:
var object = {
Sub:[{name: "X", prop: "a property"},{name: "Y", prop: "another prop"}]
}
So, you can access them with the array notation you used in your question or either using a forEach for comparing values, for instance.
Hope this helps.
I have a javascript function that passes an object that contains multiple other objects, e.g.
createButtons({
normalButtons: {
button: {
type: 'website',
name: 'Website',
}
}
socialButtons: {
socialButton: {
type: 'fb-share',
name: 'Share on Facebook'
},
socialButton: {
type: 'copyUrl',
name: 'Copy Link'
}
}
});
Now i want to iterate through all the socialButtons, but when I do using a for ... in loop, it only seems to get the first item
function createButtons(options) {
for (x in options.socialButtons) {
console.log(options.socialButtons[x]);
}
}
It only logs 1 object, the Facebook one.
Am I doing something wrong or is there a better way to solve this, please let me know.
Thank you!
You are successfully looping over the properties of that object. The problem is that you only have one property.
You defined a value for socialButton and then you defined another value for socialButton.
You need to make your property names unique.
Better yet: use an array.
Your object will not gonna work as both of the items in socialButtons: have this same keys, so, the first button will be replaced with second.
I recommend changing second socialButton to socialButton2 and everything should work.
You are using same property name socialButton inside socialButtons object. This is the cause of your problem.
Changing the name name socialButton to an unique property name will help you achieving what you want.
This is my object:
var example = {"119":{"bannerId":"119","overlay":"3","type":"1",...},"210":{"bannerId":"210","overlay":"3","type":"1",...},...}
In this way I can very easily access or modify object. For example if I want to add new property I simply call this:
example[119].newProperty = 1;
And very easily access it:
alert(example[119].newProperty)
alert(example[210].type)
By knowing banner id, I can access any data from any scope of code, this is the reason I chose this pattern. The problem is that I need to add new object inside example after it has been created. For example I need to push this into example:
{"30":{"bannerId":"119","overlay":"3","type":"1",...}}
And I don't know if this is possible. Is it? One way to solve this problem would be to use array, so example would be array and each key would carry object, and I could push into array new key with object. But I am not sure if this is proper way because key will start with 200, 300, ... console.log(example) shows undefined for all keys before 200. Is fine to have so many empty keys? Is any other better way?
EDIT:
I realized this can be done also with object. The problem was because I was trying to assign new property directly into new object like this:
example[200].example3 = 2;
guessing it is enough that example object is created. What I was missing is this line:
example[200] = {}
Thanks for answers, it works now!
var example = {};
example["30"] = {"bannerId":"119","overlay":"3","type":"1"}
console.log(example);
If its inside a loop you can also try something like below.
var i = 0;
var example = {};
for (i=0; i<10; i++) {
example[i] = {bannerId : i+1 , someOtherItem : i + "Hello"}
}
console.log(example);
example[30] = {"bannerId":"119","overlay":"3","type":"1",...};
You can always access (and assign) ad hoc keys of objects, even if you didn't define them in the first place.
So for your example you can just do:
example["30"] = {... /*your new object*/...}
It seems that you want to extend your object, you could use jQuery or underscore more or less like this:
$.extend(true, example, { "30": { objectId: "201" }}); // deep copy
If you don't want to use any library simply do:
example["30"] = myObj["30"];
Well, I'm so confused. I have made a json element like this:
var world = {"county": []};
world.county.push({name: "America", flag: "yes", countries: []});
world.county[0].countries.push({name: "Costa Rica", capital: "San Jose"});
This leads me to think two things:
I'm mixing arrays with json objects. How can I avoid using arrays in this scenario?
How can I add elements to the json root dynamically?
Regarding question 2, I'm facing issues because I don't know how to add elements to the root, let's say that I have tried this, but it doesn't work:
var index = 0;
var word = {};
world.index.push({name: WA});
So, by this way I could add elements iterating some array created previously.
First, let's get this out of the way: it's only JSON if it's a string representing a JavaScript object. What you have there is an object literal.
Now, as for your question, you can add elements to an object simply by using:
object.newProperty = value;
As for your wanting to avoid arrays, just use arrays. They are the correct type of object to use, and you shouldn't use anything else for that task.
Start with Kolink's answer. Then, for what you are doing here:
var index = 0;
var world = {};
world.index.push({name: "WA"});
It looks like you are trying to add a property to world with the index 0. Given you are then trying to use .push() it would seem you want that property to be an array, in which case you would do that like this:
world[index] = [];
world[index].push({name: "WA"});
Given that world started as an empty object that would create this structure:
{ "0" : [ {name:"WA"} ] }
In a general sense, to access an object property where the property is in a variable you use the [] array-style syntax. So:
world["somePropName"]
// does the same thing as
world.somePropName
// so with a variable:
var x = "somePropName";
world[x]
I need a user to be able to perform these actions:
Click an "Add" button. This will add a JavaScript object to either an array, or another JavaScript object.
Click a dynamic "Remove" button. This will remove the JavaScript object from the array, or object, whose ID matches the button click.
Submit the complete array, or object, of desired objects server-side for processing.
Using an array, am I able to get a handle via ID on a specific element and remove it with a "pop"-like function? If not, am I able to do so using a JavaScript object?
This question is related to this post, but there isn't much context in the original to answer my question. Thanks!
You can append an element to an array using the push method, like this:
var someArray = []; //Start with an empty array
//Later,
someArray.push({ name: 'value' });
It may actually be better to use an object rather than an array. This will allow you to name each object you send back to the server.
var dataObject = {};
function addData(name, data1, data2, data3) {
dataObject[name] = {
data1: data1,
data2: data2,
data3: data3
};
}
function removeData(name) {
delete dataObject[name];
}