Js dynamic object with dynamic arrays - javascript

Hi I am creating dynamic filter like this
Filter 1
--property 1
--property 2
--property 3
Filter 2
--property 1
--property 2
--property 3
Thats the code
var js_filter = {};
var creators_cat = [];
$('.filter-item input').on('change',function (e) {
var filter_type = $(this).attr('name');
var filter_term = $(this).val();
creators_cat.push( filter_term );
js_filter["'"+filter_type+"'"] = creators_cat;
console.log(js_filter);
})
and that's a response I get
{'filter-product_cat[]': Array(4), 'filter-brands': Array(4)}
'filter-brands': (4) ['32', '29', '23', '36']
'filter-product_cat[]': (4) ['32', '29', '23', '36']
[[Prototype]]: Object
as you can see array keys are dynamically added but values are the same for both of the keys.
An I need to add these separately.
Been looking for answer for quiet some time and didn't find something similar.
Would appreciate any help.

You shouldn't be pushing onto a global array. Each filter input should have its own array of values.
Check if there's already an element of the js_filter object for the current filter_type. If not, create it as an empty array. Then push the current value onto the array.
$('.filter-item input').on('change', function(e) {
var filter_type = $(this).attr('name');
var filter_term = $(this).val();
if (!js_filter[filter_type]) {
js_filter[filter_type] = [];
}
js_filter[filter_type].push(filter_term);
console.log(js_filter);
})

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

How to insert new value into array as per key value using Javascript

I need one help. I need to insert one new value into existing array by matching the key value using Javascript.I am explaining the scenario below.
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
]
The above is my existing array.I need to match with the below another array.
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
Here i need to match the array arr with an array galArr if image name will same this checked:true will add in the rective row of existing array galArr. Suppose arr[0].image==galArr[0].image then checked:true will add in that respective row of existing array. Please help me.
This should be sufficient.
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
];
// start looping over `arr`
arr.forEach(function(o, i){
// now loop over `galArr` to find match
galArr.forEach(function(gO, i){
// when there is a match
if(o.image == gO.image){
console.log(gO);
// add checked property to this object
gO['checked'] = true;
}
});
});
// Output
console.log(galArr);
First of all check condition and if the condition match then create a new temp json and replace it with old json
arr.forEach(function(d){
galArr.forEach(function(e){
if(e.image==d.image){
temp = {};
temp.image = e.image;
temp.comment = e.comment;
temp.checked = e.comment;
temp.action = e.action;
e = temp;
}
});
});
I would create an image index, where its indexes would be the whole image file names and later I would use that image index to quickly check and add checked property to galArr array:
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var imageIndex = galArr.map(function(item) {
return item.image;
});
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
arr.forEach(function(item) {
item.checked = imageIndex.indexOf(item.image) > -1;
});
If your users will use your JavaScript code within a modern Web browser, I would use the new Set collection:
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var imageIndex = galArr.reduce(function(result, item) {
result.add(item.image);
return result;
}, new Set());
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
arr.forEach(function(item) {
item.checked = imageIndex.has(item.image);
});
I've asked a question to assist everyone in understanding how valueable are sets: Is Set a hashed collection in JavaScript?

AngularJS How to group/organize items in object in order to show them in the view

I have a URL with some parameters like this one:
http://localhost:9000/#/checkout/?title1=Sodadrink&quantity1=2&price1=129.95&title2=PolaryteGlasses&quantity2=1&price2=59.95#%2F
and I'm getting them with $location.search(), which returns them just fine in an Object like:
Object
price1: "129.95"
price2: "59.95"
quantity1: "2"
quantity2: "1"
title1: "Sodastream"
title2: "Polaryte – Óculos de Sol"
__proto__: Object
This is cool, but now I need to group each item like:
[item]
title : Sodastream
price : 129.95
quantity : 1
[item]
title : ---
price : ---
quantity : ---
I'm stuck in this part, I've though of counting the total items inside the object, 6, and them group them in groups of 3 by creating a new Object, but didn't work out.
Can you help me? Thanks.
Since the number of items in the URL may vary, it is best to not hardcode any number. For this, I am also assuming that every item has 3 properties - title, price and quantity.
Try this:
var numOfItems = Object.keys(input).length/3; // for example, 6 properties will mean 2 items
var output = [];
for (var i = 1; i <= numOfItems; i++) {
if (input["title"+i]) {
output.push({title: input["title"+i], price: input["price"+i],quantity: input["quantity"+i]})
}
}
The output array should contain the objects in the exact way you specified.
You will have to write a bit of javascript to do that.
Assuming that your object from above is called inputs
const MAX_ITEMS=9;
var outputs = [];
for (var i=1,i<MAX_ITEMS;i++) {
if (inputs["item"+i]) {
outputs.push({item: inputs["item"+i], price: inputs["price"+i],quantity: inputs["quantity"+i]})
}
}
Your data will be in the outputs variable

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.

unique values in array count

I have an array like the following
var data = [
["1"," 101_30.1.101_34","0.0200112629","mm/s","[OK]"],
["1"," 101_30.1.101_35","0.0146548533","mm/s","[OK]"],
["1"," 101_30.1.101_45","0.0146548533","mm/s","[OK]"],
["1"," 101_42.2.101_43","0.0101406257","mm/s","[OK]"],
["2"," 102_17.3.102_38","5.1719756","mm/s","[WA]"],
["2"," 102_17.3.102_39","3.5886707","mm/s","[WA]"],
["2"," 102_17.3.102_44","9.4615074E-4","mm/s","[OK]"],
["2"," 102_40.4.102_41","4.8159785","mm/s","[OK]"],
["3"," 204_15","3.8374166","mA","[OK]"],
["4"," 501_11","1027.5156","RPM","[WA]"]
]
What im trying to do is find how many unique array there are. Example 1=4,2=4,3=1,4=1
The data is coming from a database, so the number of arrays can always change.
Here is a simple jsfiddle of what im talking about JsFiddle
Try something like this:
var count = {};
$.each(data, function(){
var num = this[0]; // Get number
count[num] = count[num]+1 || 1; // Increment counter for each value
});
console.log(count); // {1: 4, 2: 4, 3: 1, 4: 1}

Categories