How can i send objects as parameter Javascript - javascript

I need to pass an array as parameter but i have a problem, i dont know how to explain it so here is the example:
I have this code:
var doc = document;
var Class = {};
Class.Validate = function(opc)
{
alert(opc.id);//
return Class;// when returns the object the alert trigger as expected showing "#name"
};
Class.Validate({
id: "#name",
})
But what im trying to do is this:
var Class = {};
Class.Validate = function(opc)
{
alert(opc.name);//when the object is return show display "carlosmaria"
return Class;//
};
Class.Validar({
name: {field:"carlos",field:"maria"},
})
how can i archived that?

alert(opc.name) should return something like {Object object} because it's an objet. The second point is that your object has twice "field" as property.
If you want to use an array, you should call this way:
Class.Validar({
name: ["carlos", "maria"]
})
Then, you could loop over opc.name to concatenate a full name. Something like this:
Class.Validate = function(opc)
{
var name = "";
for (var i=0, len=opc.name.length; i<len; ++i) {
name += opc.name[i];
}
alert(name);//when the object is return show display "carlosmaria"
return Class;//
};

Consider using actual arrays (via array literals):
Class.Validate({
name: ["carlos", "maria"]
});

Related

Dynamically create array of objects, from array of objects, sorted by an object property

I'm trying to match and group objects, based on a property on each object, and put them in their own array that I can use to sort later for some selection criteria. The sort method isn't an option for me, because I need to sort for 4 different values of the property.
How can I dynamically create separate arrays for the objects who have a matching property?
For example, I can do this if I know that the form.RatingNumber will be 1, 2, 3, or 4:
var ratingNumOne = [],
ratingNumTwo,
ratingNumThree,
ratingNumFour;
forms.forEach(function(form) {
if (form.RatingNumber === 1){
ratingNumOne.push(form);
} else if (form.RatingNumber === 2){
ratingNumTwo.push(form)
} //and so on...
});
The problem is that the form.RatingNumber property could be any number, so hard-coding 1,2,3,4 will not work.
How can I group the forms dynamically, by each RatingNumber?
try to use reduce function, something like this:
forms.reduce((result, form) => {
result[form.RatingNumber] = result[form.RatingNumber] || []
result[form.RatingNumber].push(form)
}
,{})
the result would be object, with each of the keys is the rating number and the values is the forms with this rating number.
that would be dynamic for any count of rating number
You could use an object and take form.RatingNumber as key.
If you have zero based values without gaps, you could use an array instead of an object.
var ratingNumOne = [],
ratingNumTwo = [],
ratingNumThree = [],
ratingNumFour = [],
ratings = { 1: ratingNumOne, 2: ratingNumTwo, 3: ratingNumThree, 4: ratingNumFour };
// usage
ratings[form.RatingNumber].push(form);
try this its a work arround:
forms.forEach(form => {
if (!window['ratingNumber' + form.RatingNumber]) window['ratingNumber' + form.RatingNumber] = [];
window['ratingNumber' + form.RatingNumber].push(form);
});
this will create the variables automaticly. In the end it will look like this:
ratingNumber1 = [form, form, form];
ratingNumber2 = [form, form];
ratingNumber100 = [form];
but to notice ratingNumber3 (for example) could also be undefined.
Just to have it said, your solution makes no sense but this version works at least.
It does not matter what numbers you are getting with RatingNumber, just use it as index. The result will be an object with the RatingNumber as indexes and an array of object that have that RatingNumber as value.
//example input
var forms = [{RatingNumber:5 }, {RatingNumber:6}, {RatingNumber:78}, {RatingNumber:6}];
var results = {};
$.each(forms, function(i, form){
if(!results[form.RatingNumber])
results[form.RatingNumber]=[];
results[form.RatingNumber].push(form);
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HIH
// Example input data
let forms = [{RatingNumber: 1}, {RatingNumber: 4}, {RatingNumber: 2}, {RatingNumber: 1}],
result = [];
forms.forEach(form => {
result[form.RatingNumber]
? result[form.RatingNumber].push(form)
: result[form.RatingNumber] = [form];
});
// Now `result` have all information. Next can do something else..
let getResult = index => {
let res = result[index] || [];
// Write your code here. For example VVVVV
console.log(`Rating ${index}: ${res.length} count`)
console.log(res)
}
getResult(1)
getResult(2)
getResult(3)
getResult(4)
Try to create an object with the "RatingNumber" as property:
rating = {};
forms.forEach(function(form) {
if( !rating[form.RatingNumber] ){
rating[form.RatingNumber] = []
}
rating[form.RatingNumber].push( form )
})

Problems in accessing sub properties from separate JavaScript file

I was trying to access sub-properties from a javascript file and it's giving me something weird!
Suppose this is my JS file named data.js
module.exports = {
something: {
name: "Something",
num: 1,
email: "something#gmail.com"
},
somethingtwo: {
name: "Something Something",
num: 2,
email: "somethingtwo#gmail.com"
},
};
In my main js file named app.js, where I need to access it, it looks like
var persons = require('./data.js');
var getAName = function() {
for(var name in persons) {
console.log(name.email);
}
}
I really don't know what goes wrong but I have been trying this for quite a long time now. The expected output is the email Ids from the data.js file but instead, i get undefined times the number of entries (if there are 2 entries in data.js, then I get 2 undefine and so on).
How can I access the email or the num from the data.js without those undefines?
console.log(name) is returning something somethingtwo
Well, name.email is undefined because name is a string.
You can test that by writing
console.log(typeof name);
Now, to solve your problem, you need to access the property correctly:
var getAName = function() {
for (var name in persons) {
console.log(persons[name].email)
}
}
Returns:
something#gmail.com
somethingtwo#gmail.com
for(var name in persons) {
//persons is actually an object not array
//you are actually iterating through keys of an object
//var name represent a key in that object
console.log(persons[name]); //value corresponding to the key
}
I guess this code will give you the desired result.
You should be using console.log(persons[name].email)
require don't automatically calls the module
var DataArchive = require('./data.js');
var module = DataArchive.module;
var persons = module.exports;
var getAName = function() {
for(var person in persons) {
//person should be something (first iteration) and somethingtwo (second iteration)
console.log(person.email);
}

How would I go about using a multidimensional array variable in javascript

Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.

Can I put an object and an array together inside another array?

I have two objects which i want to group together in an object then place them both inside an array.
vm.data = {};
vm.category_name_image = [] ;
getProductFunc=function(){
$http.get(ConfigCnst.apiUrl+'?route=categories').success(function (res) {
//console.log(res);
var sub_category = res;
console.log(sub_category);
var bagmankey = '-JweP7imFLfnh96iwn-c';
//console.log(bagmankey);
angular.forEach(sub_category, function (value, key) {
if (value.parentKey == bagmankey ) {
// where i loop
vm.data.name = value.name;
vm.data.picture = value.image;
var selected = {
vm.data.name,
vm.data.picture
} // Where I group the two.
vm.category_name_image.push(seleted);
// where i want to place the both.
}
});
});
}
I seem to be getting an error when I place both vm.data.name and vm.data.picture, inside the object selected.
I want my output like this: [ {name,picture},{name,picture},{name,picture} ]
You can't create object property without name:
//object with properties 'name' & 'picture'
var selected = {
name: vm.data.name,
picture: vm.data.picture
}
or You can use array, if You really need use only data (bad way):
var selected = [
vm.data.name,
vm.data.picture
]
Javascript objects are key value pairs. You are missing the key when you construct the object
var selected = {
name: vm.data.name,
picture: vm.data.picture
} // Where I group the two.
You could directly push by the way without using selected
vm.category_name_image.push({
name: vm.data.name,
picture: vm.data.picture
});
You have a typo in your example.
var selected = {
vm.data.name,
vm.data.picture
}; // Where I group the two.
vm.category_name_image.push(seleted);
// where i want to place the both.
It should be
//it would be better to assign name and picture to properties of the object
var selected = {
name: vm.data.name,
picture: vm.data.picture
}; // Where I group the two.
//you had a typo here --- it should be selected not seleted
vm.category_name_image.push(selected);
// where i want to place the both.
// where i loop
vm.data.name = value.name;
vm.data.picture = value.image;
var selected = {
vm.data.name,
vm.data.picture
} // Where I group the two.
vm.category_name_image.push(seleted);
// where i want to place the both.
}
You can use below code instead
vm.category_name_image.push({name:value.name, picture:value.image});

How to increment nested objects with variable names in MongoDB

So the code I'd 'like' to work is below. I have a variable name as the name of the key of the object unread, which seems to be in the only way of doing this in MongoDB is by creating an object outside and referencing it as the value for $inc. This doesn't seem to work, it does work however if I just have a key partnerId without nesting the object. My question is how do i get it working with nested objects.
Does work:
var partnerId = 234567;
var action = {
unread: {}
};
action[partnerId] = 1;
Threads.update(Session.get('currentChat'),
{
$inc: action
}, callback);
Does not work, but would like it to work:
var partnerId = 234567;
var action = {
unread: {}
};
action.unread[partnerId] = 1;
Threads.update(Session.get('currentChat'),
{
$inc: action
}, callback);
I get an error about not being able to increment things that aren't numbers, which I guess is refering to the object within the object.
The schema I have is like this, with 123456 and 234567 as user ids and I just want to increment that number:
{
_id: 123,
unread: {
123456: 0,
234567: 1,
}
}
If you wanted to write this out in a non-dynamic way, you'd do:
var id = Session.get('currentChat');
Threads.update(id, {$inc: {'action.unread.234567': 1}});
$inc needs to take an object with a dynamically created key based on partnerId like so:
var partnerId = 234567;
var key = 'action.unread.' + partnerId;
var obj = {};
obj[key] = 1;
Now obj looks like:
{'action.unread.234567': 1}
So we can plug that into your original code:
Threads.update(id, {$inc: obj}, callback);

Categories