JavaScript Array Issue with data['sax'] - javascript

I have a confusion of what this array can hold. Also, I want to know how it assigns the values to the variable set.
Can someone give me an example of data['sax'] please and explain me the loop below?
for(var x = 0; x < data['sax'].length; x++){
var set = data['sax'][x];
Then what does this mean ?
id : set.saxID,
name : set.symbol

What you have here is an array that is being looped through. data['sax'] will be something along the lines of the following:
var data = {
sax: [
{
saxID: 1,
symbol: 1
},
{
saxID: 2,
symbol: 2
}
]
}
As you can see in the example above, sax is an array which contains multiple objects. What happens when you loop over it, is that it accesses one of the objects inside the array. So data['sax'][0] will give you the object with saxID: 1.
Using the variable set to temporarily store the data in; you can access the data of data['sax'][0] as set. So data['sax'][0].saxID becomes set.saxID. It is somewhat of a shorthand version of accessing the data.
What happens with id: set.saxID, is that the values get assigned to a new object. Which will be something like the following.
var newSax = {
id: set.saxID
}
You are basically transferring data from one object to another.

Explaining the code
var set = data['sax'][x];
Here you are creating a variable called set and assigning it a value from data['sax'][x].
data['sax'] this might look like a array But Its Not, to access value of a array we use index but here its a string. This is another way of accessig a property value of a object. So data is a object with one of its property being sax. That means
data = {sax: somevalue};
Now we have,
data['sax'][x] So as you know data['sax'] is a object and then this [x] , here x is not a string its a variable and it holds the Number value (0,1,2,3...) , it means your data['sax'] value is a array since we are accessing from index.
So from the above analysis your data['sax'] will be in this format.
Array
data = { sax : ["someValue","someValue"]}
So variable set will be
var set = "someValue"; // if x = 0, as in the first loop
Now coming to the code
id : set.saxID,
name : set.symbol
set.saxID this is used if the set is an object. In Jquery to retrieve the value of a property in the object you use the . operator with property name (or by the property name as seen above). So the code means set is a object with two properties saxID and symbol. So your set object will be like
set = { saxID: 123, symbol = "TEST"}
That also means that your data value be
data = { sax : [{saxID: 123, symbol = "TEST"},{saxID: 123, symbol = "TEST"}]}
Let me know if I was clear

Related

Accessing Value in Array Object with Generic Variable for Key

I recognize that I can access the value of an object within an array by passing in the key name, like so:
const batchNumValue = batchNumber[0]['MAX(batch_number) + 1'];
In my case I know the array will always contain exactly one object, with a single key/value pair, like so:
[{ 'MAX(batch_number) + 1' : 234 }]
That being the case, my question is, is there a way I can pass in a variable representing whatever that key name happens to be? Or does one have to always explicitly pass the key name, even in a situation like this?
You could get the values from the object and take the first item.
const
data = [{ 'MAX(batch_number) + 1' : 234 }],
value = Object.values(data[0])[0];
console.log(value);

how to pass a dynamic key value from a string in mongo data base

I try to dynamically access a field in mongo database.
The target field is given by this line:
var contextTarget= Session.get('contextLayout')+"BackgroundColor";
Where
Session.get('contextLayout') could be either a string or an _id of a collection(eg. userHomeBackgroundColor or 56xhPYg8w3Qtv9xPLBackgroundColor).
I don't know how to access the value.
I tried this code:
var contextTarget= Session.get('contextLayout')+"BackgroundColor";
var tempStore ={};
tempStore['target']=contextTarget;
var newTarget = tempStore.target;
console.log(newTarget);//return the correct value
var color = customConfiguration.findOne({'author':auth}).newTarget;
console.log(color);//return undefined
It doesn't work. I suppose that it's because the newTarget variable is a string because if I directly write the expected result in the console, it works.How can I do?
EDIT.
like said BraveKenny:
var color = customConfiguration.findOne({'author':auth})[contextTarget];
In fact, it was not necessary to pass by the object tempStore. With the square brackets keys are properly sent. I had already try it but with a dot before the square bracket.
#Michael: For the schema, I don't have a schema for this collection, because the key names are dynamically created.
Thanks a lot.
If I understand correctly, in the end, you want to get a variable attribute of your customConfiguration object, which name is contained in newTarget.
Maybe try this instead:
var color = customConfiguration.findOne({'author':auth})[newTarget];
Basically when you type:
someObject.toto = 'someValue';
var someAttribute = 'toto';
console.log(someObject.someAttribute); //undefined
console.log(someObject[someAttribute]); // 'someValue'
JavaScript will always assume someAttribute is an attribute of someObject when it's called with a dot notation. Not a variable set in the scope. If you want the value of an attribute toto which is contained in a string variable (in my case, someAttribute), you have to pass this variable as an index, like this:
console.log(someObject[someAttribute]); // 'someValue'
It would be helpful if you could describe the schema of the collection customConfiguration. I just guess that it contains a collection of documents with just one property each (e.g. userHomeBackgroundColor or 56xhPYg8w3Qtv9xPLBackgroundColor) and you are interested in the one document with the correct property name to read the property value. So I guess, in JSON notation the collection looks something like this:
[
{"userHomeBackgroundColor": "red"},
{"56xhPYg8w3Qtv9xPLBackgroundColor": "green"},
{"someOtherConfigProperty" : "someOtherValue"}
]
If this assumption is correct, I would replace your original line
var color = customConfiguration.findOne({'author':auth}).newTarget;
With something like this:
var selector = {}; // Empty selector object for findOne
selector[contextTarget] = // Add dynamic property and as its value
{$exists: true}; // an object with an $exists-property
// with value true
// now find the (first) configuration document having the dynamic property
var configDocument = customConfiguration.findOne(selector);
// read the value of the dynamic property of the configuration document
var color = configDocument[contextTarget];
But to verify this, I need more background about the schema of the collection customConfiguration. You might also want to check the documentation of $exists (http://docs.mongodb.org/manual/reference/operator/query/exists/#op._S_exists) and findOne() (http://docs.mongodb.org/manual/reference/method/db.collection.findOne/) in the documentation.
If, however, the collection customConfiguration contains one configuration document for each author, change your line to just this:
var color = customConfiguration.findOne({'author':auth})[newTarget];
This solution has been described in a previous answer.

find and replace property value in json object using javascript/underscore.js

I have one list as follows
var data = [{id:1, name:'user1', img:'img1.jpg' },{id:2, 'user2', img:'img2.jpg' }]
Now I have to replace img property with new value (e.g. 'New_Image_2.jpg') for id=2 using underscore.js or in javascript using less effort. right now I have created one small function as follows.
var imgpath = 'New_Image_2.jpg';
var tmpdata = _.findWhere(data,{id:2});
if (tmpdata) {
tmpdata.img = imgpath;
}
Now, in above method, my problem is, How to marge new value with original data?
Well your code should already work because _.findWhere returns the first object corresponding to your constraint or undefined if it does not exist, it means that modifying tmpdata.img actually modifies the value you want to modify.

Dynamically add variable name as part of object in Javascript/jQuery

I'm trying to create an object which references a number of forms which I can JSON.stringify() to send through to a validation script with a single AJAX request, but I can't seem to properly name the array inside the object, which should be an incrementing count as the number of arrays (forms) increases.
i.e.
var images = new Object();
var i = 0;
// loop through every form
$('form').each(function() {
var form = $(this);
images[i].name = form.find('input[name="name"]').val();
images[i].description = form.find('textarea[name="description"]').val();
// etc.
i++;
});
So, when complete after say two to three iterations (that is, it's gone through two-three forms), I have a Javascript object similar to this (written in pseudocode, I'm not exactly too sure how it's actually outputted):
images {
0 {
name : 0thImageNameValueHere,
description : 0thImageDescripValueHere,
etc : etc
}
1 {
name : 1stImageNameValueHere,
description : 1stImageDescripValueHere,
etc : etc
}
}
But, right now, Firebug is giving me a SyntaxError: missing ; before statement error, centered around this line:
images[i].name = form.find('input[name="name"]').val();
Now, I can change the 'value' of images[i].name to anything I like (images[i].name = 'yes') and I still get the same error. Syntactically I'm not missing any semi-colons, so it can't be that. Is it possible I'm not declaring my object correctly?
Images is an array ([]). Your syntax does not comply with this situation (you expect an object). Create an object for each item in the array, then you can assign values to the attributes of this object.
Also, you can just make use of the index parameter provided by jQuery, you don't have to create your own iterator.
This does what you want:
var images = []; // create an array
$('form').each(function( index ) {
var form = $(this);
// create object with {} object notation
var image = {
name: form.find('input[name="name"]').val(),
description: form.find('textarea[name="description"]').val()
};
images[index] = image; // append object in array position index;
}
See for more info on objects the JSON WIKI.
See for more info on arrays W3Schools.
I don't know about any missing semi colon, but you need to create an object at images[i] before you assign any properties on it. Ie try this:
images[i] = {
name: get('input[name="name"]').val(),
description: get('textarea[name="description"]').val()
};
You can also use the index parameter supplied by each():
$('form').each(function(i) { ... }

JavaScript: How to efficiently replace all values of an object without replacing the object

I have a number of objects collected in an array. The same objects are also attached to certain DOM elements for various reasons. From time to time I need to update one of these objects. The easiest way to do this is to find the object in the array with the same id property as the one I got new values for through AJAX and then replace it. But this of course creates a new object and the objects attached to DOM elements are no longer the same. Which means that if I would compare them they would not be the same object anymore.
How can I easiest replace the correct object with the values in the new object without replacing the actual object? (So that the reference remains the same)
Example of what I don't want
var values = [{id:1, name:'Bob'}, {id:2, name:'Alice'}, {id:3, name:'Charlie'}];
var bar = values[2];
console.info(bar === values[0]); // True
var newValue = {id:1, name:'Dave'};
// Somehow find the index of the object with id==3
values[2] = newValue;
console.info(bar === values[2]); // False, should still be true
Only way I can think of is looping through the object with a foreach or something, but hoping there is something built-in to javascript or jQuery or something that allows for more efficient or at least cleaner code.
You can iterate the values of the new one and set them in the old one:
for (i in newValue) {
oldValue[i] = newValue[i];
}
You could use the handle/body pattern, so the objects in the array only have a single property, which has all the real properties for the object:
var values = [{values:{id:1, name:'Bob'}}, {values:{id:2, name:'Alice'}}, {values:{id:3, name:'Charlie'}}];
var bar = values[2];
console.info(bar === values[0]); // True
var newValue = {id:1, name:'Dave'};
// Somehow find the index of the object with id==3
values[2].values = newValue; // set the values of the object, not the object
console.info(bar === values[2]); // Still true
I'd advise you to replace the objects attached to DOM elements at the same time that you replace the objects in your array. That way, the comparison still holds true.
If that's not possible, then in your example we can see that you only really replace the name property. So you just have to copy the name property from the Ajax object to the Array object.

Categories

Resources