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

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});

Related

How to push additional fields to a javascript array from an oData result

I have a ramdom array in javascript
var dataModel = [];
I've queried an oData url and I want to fill the result in my dataModel [] array. And, for each item I want to add additional fields
odataMod.read(
"/",
null, [],
true,
function (oData, oResponse) {
var data = oData.results;
data.forEach(function (item) {
//Add the object
dataModel.push(item);
//I want to add additional fields to every object in data
dataModel.push(item.ObjectType = "Chevron");
dataModel.push(item.HierarchyNodeLevel = 0);
dataModel.push(item.IsCriticalPath = false);
dataModel.push(item.IsProjectMilestone = false);
dataModel.push(item.DrillDownState = "expanded");
dataModel.push(item.Magnitude = 5);
...
Note : the ObjectType , DrillDownState , Magnitude (etc...) are the fields that I want to add with their values Chevron, 0, false (etc...)
Below is a screenshot of the current result :
But I want to add the additional properties inside each item and not outside , what I am doing wrong? In other word, I want the additional fields to be inside the metadata
Below is a sc of where I would like to add the items :
Maybe I'm misunderstanding, but I think you want only one push per item in the response. The other pushes ought to be replaced with setting properties on a copy of the item...
data.forEach(function (item) {
item.ObjectType = "Chevron";
item.HierarchyNodeLevel = 0;
item.IsCriticalPath = false;
item.IsProjectMilestone = false;
item.DrillDownState = "expanded";
item.Magnitude = 5;
dataModel.push(item); // note: just one push
// alternatively, so as to not mutate item...
// const dataModelItem = Object.assign({
// ObjectType: "Chevron",
// HierarchyNodeLevel: 0,
// etc.
// }, item);
// dataModel.push(dataModelItem);
}

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 )
})

Create an array of Objects from JSON

I have a JSON file like below:
[
{"fields":{category_class":"CAT2",category_name":"A"},"pk":1 },
{"fields":{category_class":"CAT1",category_name":"B"},"pk":2 },
{"fields":{category_class":"CAT1",category_name":"C"},"pk":3 },
{"fields":{category_class":"CAT2",category_name":"D"},"pk":4 },
{"fields":{category_class":"CAT3",category_name":"E"},"pk":5 },
{"fields":{category_class":"CAT1",category_name":"E"},"pk":6 },
]
I want to create an array of objects from the above JSON which will have two properties. i) CategoryClass ii) CategoryNameList. For example:
this.CategoryClass = "CAT1"
this.CategoryNameList = ['B','C','E']
Basically i want to select all categories name whose category class is CAT1 and so forth for other categories class. I tried this:
var category = function(categoryClass, categoryNameList){
this.categoryClass = categoryClass;
this.categoryList = categoryNameList;
}
var categories = [];
categories.push(new category('CAT1',['B','C','E'])
Need help.
You can use a simple filter on the array. You have a few double quotes that will cause an error in you code. But to filter only with CAT1 you can use the filter method
var cat1 = arr.filter( value => value.fields.category_class === "CAT1");
I would suggest this ES6 function, which creates an object keyed by category classes, providing the object with category names for each:
function groupByClass(data) {
return data.reduce( (acc, { fields } ) => {
(acc[fields.category_class] = acc[fields.category_class] || {
categoryClass: fields.category_class,
categoryNameList: []
}).categoryNameList.push(fields.category_name);
return acc;
}, {} );
}
// Sample data
var data = [
{"fields":{"category_class":"CAT2","category_name":"A"},"pk":1 },
{"fields":{"category_class":"CAT1","category_name":"B"},"pk":2 },
{"fields":{"category_class":"CAT1","category_name":"C"},"pk":3 },
{"fields":{"category_class":"CAT2","category_name":"D"},"pk":4 },
{"fields":{"category_class":"CAT3","category_name":"E"},"pk":5 },
{"fields":{"category_class":"CAT1","category_name":"E"},"pk":6 },
];
// Convert
var result = groupByClass(data);
// Outut
console.log(result);
// Example look-up:
console.log(result['CAT1']);
Question : Basically i want to select all categories name whose category class is CAT1 and so forth for other categories class
Solution :
function Select_CatName(catclass,array){
var CatNameList=[]
$(array).each(function(){
if(this.fields.category_class==catclass)
CatNameList.push(this.fields.category_name)
})
return CatNameList;
}
This function return the Desired Category Name List, you need to pass desired catclass and array of the data , as in this case it's your JSON.
Input :
Above function calling :
Output :
Hope It helps.

For..In Loop Overwriting ALL Array Values

I'm trying to use a for..in loop to iterate through a list of names, add them to a template object ('group'), then add each complete object to an array ('queryList'). This isn't working because each iteration is overwriting ALL values in the array. Any suggestions why this is happening?
// BATTERY OBJECT
var groupList = [ "LOGIN", "BROWSE", "SEARCH"];
// GROUP OBJECT
var group = {dbName: 'CARS', name: '', collectionName: 'group'};
// INIT VARS
var groupName = '',
queryList = [];
// COMPILATION FUNCTION
var buildGroupQueries = function(group){
// BUILD BATCH OF QUERIES
for (var i in groupList){
groupName = groupList[i];
group.name = groupName;
queryList[i] = group;
}
console.log(queryList);
}
buildGroupQueries(group);
It should look like:
[
{"dbName":"CARS","name":"LOGIN","collectionName":"group"},
{"dbName":"CARS","name":"BROWSE","collectionName":"group"},
{"dbName":"CARS","name":"SEARCH","collectionName":"group"}
]
Instead I'm getting:
[
{"dbName":"CARS","name":"SEARCH","collectionName":"group"},
{"dbName":"CARS","name":"SEARCH","collectionName":"group"},
{"dbName":"CARS","name":"SEARCH","collectionName":"group"}
]
You are creating an array of elements referring to the same object, so they all show the same name coinciding with the last time you changed it, which is "SEARCH" in your example.
You have to refer each element to a new object created from the one you want to use as a template.
To do so you can either loop over its properties or clone it as shown below:
// BATTERY OBJECT
var groupList = [ "LOGIN", "BROWSE", "SEARCH"];
// GROUP OBJECT
var group = {dbName: 'CARS', name: '', collectionName: 'group'};
// INIT VARS
var groupName = '',
queryList = [];
// COMPILATION FUNCTION
var buildGroupQueries = function(group){
var i, _group;
// BUILD BATCH OF QUERIES
for (i in groupList){
_group = JSON.parse(JSON.stringify(group));
groupName = groupList[i];
_group.name = groupName;
queryList[i] = _group;
}
console.log(queryList);
}
buildGroupQueries(group);
You modify the group object each time, but you need to modify its copy.
Add this code just after your line for (var i in groupList){
var _group = {};
for (var j in group){ _group[j] = group[j]; }
On each iteration you create a new object and copy to it all properties from the master object.

How can i send objects as parameter 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"]
});

Categories