Reputation: 4927
I run trough a couple of div's with the jQuery .each function.
With console.log I get this output
0.24 240,
0.1 100,
0.24 240,
0.24 240,
The first number on each line is a factor and the last is the sum of a multiplication
I would like to make a hash like this when the each function runs
a = {0.24: 720, 0.1: 100}
The number 0.24 as key, then sum up the the second number on each 0.24 line as value and so on.
Ideas?
Update and my solution
jQuery.fn.myFunction = function(){
var hash = {}
this.each(function(index, element) {
var key = var key = $(element).attr("data-key");
var value = $(element).attr("data-value");
if (hash.hasOwnProperty(key)){
hash[key] = hash[key] + value
}else{
hash[key] = value;
}
});
console.log(hash)
}
Upvotes: 0
Views: 871
Reputation: 26302
I assume you have key and value, though it will be better if you provide at least javascript you use.
var jsonObject = {}
function makeObject(key,value)
{
jsonObject[key] = value + parseInt(jsonObject[key] == undefined ? 0 : jsonObject[key]);
jsonObject[key] = value;
}
call this function in your loop, after that jsonObject will contain desired Json Object. I hope this is near your requirement.
Edit:
jsonObject[key] = value + parseInt(jsonObject[key] == undefined ? 0 : jsonObject[key])
Update: above snippet is adding the value, if there is duplicate key then it will parse down the corresponding value to integer and then add it to the already unique key present in the json object. So, If there is no duplicate key then it will simply add 0 else it will ad the value.
Upvotes: 1
Reputation: 3612
Here's some code to illustrate an approach you could take:
var input = [{"factor":"0.24", "value": 240},
{"factor":"0.1", "value": 100},
{"factor":"0.24", "value": 240},
{"factor":"0.24", "value": 240}];
var result = {};
for (var i = 0; i < input.length; i++) {
var current = input[i];
if (typeof result[current.factor] === 'undefined') {
result[current.factor] = current.value;
} else {
result[current.factor] += current.value;
}
}
console.log(result);
seen here: http://jsfiddle.net/6ZA4f/
Hopefully you can apply this idea to your own code.
Upvotes: 0
Reputation: 525
First of all correct your object, and make keys as string:
a = {'0.24': 720, '0.1': 100}
Second: Can you show a code snippet with yhour each loop?
Upvotes: 0