I'm looping through a set of inputs. I need to tally up the grouped totals. The inputs below to one of three categories.
How do I go about combining the values up relevant to three categories?
var compoundedArray = new Array();
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
var localObj = {};
localObj[dataType] = val;
compoundedArray.push(localObj);
});
I have an object like this
[
{
"growth":30
},
{
"growth": 40
},
{
"other": 20
}
]
how do I loop through the object to produce something like
[
{
"growth": 70
},
{
"other": 20
}
]
if I looped over the initial array object
for (var i = 0; i < compoundedArray.length; i++) {
console.log(compoundedArray[i]);
}
how would I go about checking to ensure I don't have duplicates - and that I can tally up the results?
Ideally the resulting format may be the best
var array = [
"matching": 50,
"growth": 20
]
var array = [
"matching": 50,
"growth": 20
]
is not valid JS, but you can create an object of the form
var obj = {
"matching": 50,
"growth": 20
};
And that's pretty easy to do, just use an object from the very beginning:
var result = {};
holder.find(".dataset input").each(function(index) {
var val = +$(this).val(); // use unary plus to convert to number
var dataType = $(this).data("type");
result[dataType] = (result[dataType] || 0) + val;
});
Further reading material:
MDN - Working with Objects
Eloquent JavaScript - Data structures: Objects and Arrays
You can just use an object (not array) with unique keys.
var compoundedObj = {};
$(".dataset input", holder).each(function() {
var dataType = $(this).data("type");
if(!compoundedObj.hasOwnProperty(dataType)) {
compoundedObj[dataType] = 0;
}
compoundedObj[dataType] += parseInt($(this).val(), 10);
});
In this way you'll get an object like this:
{
"growth": 70,
"other": 20
}
Live demo
http://jsfiddle.net/GFwGU/
var original = [{"growth":30},{"growth": 40},{"other": 20}]
// object to sum all parts by key
var sums = {}
// loop through original object
for(var index in original){
// get reference to array value (target object)
var outer = original[index]
// loop through keys of target object
for(var key in outer){
// get a reference to the value
var value = outer[key]
// set or add to the value on the sums object
sums[key] = sums[key] ? sums[key] + value : value
}
}
// create the output array
var updated = []
// loop through all the summed keys
for(var key in sums){
// get reference to value
var value = sums[key]
// create empty object
var dummy = {}
// build object into desired format
dummy[key] = value
// push to output array
updated.push(dummy)
}
// check the results
alert(JSON.stringify( updated ))
var add=function (a,b){ a=a||0; b=b||0; return a+b};
var input=[ {growth:30},{growth:40},{other:20} ],output=[],temp={};
$.each(input,function(i,o){
var n;
for(i in o)
{n=i;break}
temp[n]=add(temp[n],o[n]);
});
$.each(temp,function(i,o){
var k={};
k[i]=o;
output.push(k)
});
Related
Hi friends I'm beginner for javascript how i sum same n no's of object name corresponding value and push the result to new array.see this is sample object
var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};
but i expect this output [UK:{'delivered':20,'due':22},US:{'delivered':10,'due':11}],so please help me what i'll do next
You can first create array of objects and then reduce() to return one object.
var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};
var result = [obj_1, obj_2, obj_nth].reduce(function(r, e) {
if(!r[e.team_name]) {
r[e.team_name] = {delivered:0,due:0}
}
r[e.team_name].delivered += e.delivered
r[e.team_name].due += e.due
return r
}, {})
console.log(result)
const newArray = initialArray.map(({team_name, ...restProps}) => {
return {
[team_name]: {...restProps}
};
});
See:
Arrow functions
Spread operator
Array.prototype.map
Computed property names
var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};
function sum_all() {
var sum={};
for(var i=0;i<arguments.length;i++) {
obj = arguments[i];
if (!sum[obj.team_name]) {
sum[obj.team_name]={'delivered':0,'due':0};
}
sum[obj.team_name].delivered += obj.delivered;
sum[obj.team_name].due += obj.due;
}
return sum;
}
var sum = sum_all(obj_1,obj_2,obj_nth);
console.log(sum);
Your console output will be:
sum
Object
UK: Object
delivered: 20
due: 22
US: Object
delivered: 10
due: 11
Store these objects in an array, such as:
var myObjects = [
{'delivered':10,'due':11,'team_name':'UK'},
{'delivered':10,'due':11,'team_name':'US'},
{'delivered':10,'due':11,'team_name':'UK'}
];
Create a new object in which you will store your results:
var results = {};
Then iterate through the array with a for loop (as it is generally faster) and add the other properties according to team_name:
for (var i = 0; i <= myObjects.length; i++) {
if (typeof results[myObjects[i].team_name] !== undefined) {
results[myObjects[i]].delivered += myObjects[i].delivered;
results[myObjects[i]].due += myObjects[i].due;
} else {
// Set 0 to these properties if the entry didn't exist
results[myObjects[i]].delivered = 0;
results[myObjects[i]].due = 0;
}
}
I have a caml query which is going to return something like this in xml.
ID Title Percentage
7;#7 2 1.00000000000000
7;#7 3 0.220000000000000
7;#7 sub 1.1 0
7;#7 4 0.140000000000000
12;#12 7 0.670000000000000
13;#13 6 0.700000000000000
I'll likely create an aray of objects for each item. Something like this:
var result = [{id:7,title:"2",percent:1.0},...,{id:13,title:"6",percent:0.7}]
How could I iterate through the result and add up all the percentages with the same ID so I end up with something like:
var total = [{id:7,percent:1.36,count:4},{id:12,percent:0.67,count:1},{id:13,percent:0.7,count:1}]
Or even if I could just get
percent/count = totalPercentage so I end up with an object with just {id:7,totalPercentage:0.325}
Try this:
var percentages = {};
result.forEach(function (it) {
var obj = percentages[it.id] = percentages[it.id] || {
percent: 0,
count: 0,
id: it.id
};
obj.percent += Number(it.percent); // Casting to Number, in case percent comes as string
obj.count++;
});
This creates an object, with ids as keys. Should you wish to convert it to an array:
total = Object.keys(percentages).map(function (it) {
return percentages[it]
});
To get the average of the percentages, you can do this:
total = total.map(function(it) {
return {
id: it.id,
percent: it.percent / it.count
};
});
Just make the new object and iterate though the old one. You can see a demo here: http://jsfiddle.net/TSyE5/2/
var totalPercent = [],
total = {},
result = [{id:8,title:"3",percent:1.0},{id:7,title:"2",percent:1.0},{id:7,title:"2",percent:3.0},{id:13,title:"6",percent:0.7},{id:13,title:"6",percent:0.7},{id:13,title:"6",percent:0.7}];
$.each(result, function(){
!(this.id in total) && (total[this.id] = {id:this.id, title:this.title, percent:0, count:0});
total[this.id].percent += this.percent;
total[this.id].count++;
});
$.each(total, function(i){
total[i].percent = total[i].percent/total[i].count;
totalPercent.push({id:total[i].id, percent:total[i].percent});
});
This question already has answers here:
How to put items into grouped arrays where grouped by a particular key
(3 answers)
Closed 9 years ago.
I have a parent object. I want to create child objects from the parent with the same key value pair.
e.g.
parentJSON = {[name:"a1",address:"b1",comp:"c1"],
[name:"a2",address:"b2",comp:"c1"],
[name:"a3",address:"b3",comp:"c2"],
[name:"a4",address:"b4",comp:"c2"],
[name:"a5",address:"b5",comp:"c2"],
[name:"a6",address:"b6",comp:"c3"]}
Now I want to create child objects having same "comp" value.
e.g.
childJSON1 = {[name:"a1",address:"b1",comp:"c1"],
[name:"a2",address:"b2",comp:"c1"]}
childJSON2 = {[name:"a3",address:"b3",comp:"c2"],
[name:"a4",address:"b4",comp:"c2"],
[name:"a5",address:"b5",comp:"c2"]}
childJSON3 = {[name:"a6",address:"b6",comp:"c3"]}
This is what I tried to make it little bit (it will change the parent object with a key indicating number of repetition):
parentJSON = [1,2,3,3,4,4,4,5];
var i=0, x, count, item;
while(i < parentJSON.length) {
count = 1;
item = parentJSON[i];
x = i+1;
while(x < parentJSON.length &&
(x = parentJSON.indexOf(item, x)) != -1) {
count += 1;
parentJSON.splice(x,1);
}
parentJSON[i] = new Array(parentJSON[i],count);
++i;
}
console.log(parentJSON);`
first of all your json is in the incorrect format, it should look like this
[{name:"a1",address:"b1",comp:"c1"},
{name:"a2",address:"b2",comp:"c1"},
{name:"a3",address:"b3",comp:"c2"},
{name:"a4",address:"b4",comp:"c2"},
{name:"a5",address:"b5",comp:"c2"},
{name:"a6",address:"b6",comp:"c3"}]
An array of objects.
My attempt, also very readable.
var result = {};
$.each(parentJSON, function (i, item) {
if(!result[item.comp]) {
result[item.comp] = [];
}
(result[item.comp]).push(item);
});
alert(JSON.stringify(result))
JsFiddle
First of all your json is actually invalid. You may have an array of objects, but not object which contains an array like that. Also your arrays looks more like objects, because the syntax with the dots is used for objects. Here is how I guess should look like:
var parentJSON = [
[{name:"a1",address:"b1",comp:"c1"}],
[{name:"a2",address:"b2",comp:"c1"}],
[{name:"a3",address:"b3",comp:"c2"}],
[{name:"a4",address:"b4",comp:"c2"}],
[{name:"a5",address:"b5",comp:"c2"}],
[{name:"a6",address:"b6",comp:"c3"}]
];
var child1 = parentJSON.slice(0, 2);
var child2 = parentJSON.slice(2, 5);
And you may use the .slice method to get specific elements of the array.
So..you need to clone objects?
maybe tou can try sth like this:
var sergi= {
name: "sergi",
age: 33
};
var bill = (JSON.parse(JSON.stringify(sergi)));
bill.name = "Bill";
console.log(sergi);
console.log(bill);
parentJSON = function(){
return [
{name:"a1",address:"b1",comp:"c1"},
{name:"a2",address:"b2",comp:"c1"},
{name:"a3",address:"b3",comp:"c2"},
{name:"a4",address:"b4",comp:"c2"},
{name:"a5",address:"b5",comp:"c2"},
{name:"a6",address:"b6",comp:"c3"}
];
}
childJSON1 = new parentJSON().slice(0,2);
childJSON2 = new parentJSON().slice(2,5);
childJSON3 = new parentJSON().slice(5,6);
Try this:
DEMO
var data = [
[{name:"a1",address:"b1",comp:"c1"}],
[{name:"a2",address:"b2",comp:"c1"}],
[{name:"a3",address:"b3",comp:"c2"}],
[{name:"a4",address:"b4",comp:"c2"}],
[{name:"a5",address:"b5",comp:"c2"}],
[{name:"a6",address:"b6",comp:"c3"}]
];
var groups = {};
$.each(data, function(i, item) {
var comp = item.comp;
delete item.comp;
if(groups[comp]) {
groups[comp].push(item);
} else {
groups[comp] = [item];
}
});
var result = $.map(data, function(group, key) {
var obj = {};
obj[key] = group;
return obj;
});
alert(JSON.stringify(groups))
I have a question about array as below
array = {}
and
array = [];
its same or not?.
also wish to ask
array { ID1 : "apple", ID2 : "Orange"}
and
array [ID1 : "apple", ID2 : "Orange"];
which is correct?.
now i coding my code with below and need your help to teach me about ARRAY.
var Store = [ store = 0, store1 = 0, store2 = 0,store3 = 0,store4 = 0];
var stock1 = 77,stock2 = 47,stock3 = 37,stock4 = 27,stock5 = 17;
for(i=0;i<stock1;i++){
store[0]++
}
var Sum_1 = Store;
document.getElementById('show1').innerHTML=Sum_1;
output will be
77
my question is how to i output it become
store = 77
store1 = 47
store2 = 37
Most with ID or Name together and value.
Thank you so much.
[] are used for a literal Array declaration, {} for a literal Object declaration.
Arrays are initialized without a value by using:
var my_array = [];
and with values:
var my_array = [1, 2, 3];
Note that you cannot set the index by this. You would have to do:
var my_array = [];
my_array["one"] = 1;
// etc.
You can then get "1" back by my_array["one"]
If you want to get the actual index name or "key" then you will need to do some trickery:
var outputString = "";
function ListAll()
{
for(var key in my_array)
{
if(my_array.hasOwnProperty(key)) // Check if the key is actually a property (index)
{
outputString += key + " = " + my_array[key]; // add to string
}
}
alert(outputString); // or assign the string to a div, whatever you need
}
in this example, key would be the index and my_array[key] the actual value
How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});