0

Function argument is stored in such format

["2015-07-05 00:30", 59]
...
["2015-07-05 01:00", 62]
function generateCSV(timeAndValue) {
    object = {}
    var zero = 0;
    for(i = 0; i < timeAndValue.length; i++){
        var value = timeAndValue[i]
        var days = moment(value[0]).format('YYYY-MM-DD');
        obj[days] += value[1] + ', '
    }
}

In the loop object takes days as parameter and the amount of value spent on that day. 2015-07-05:

"2015-07-05: "undefined59, 62, 65...

2015-07-06: "undefined61, 61, 60..."

Every parameter value is beginning with "undefined". How can I loop that parameters wouldn't begin with "undefined"?

1 Answer 1

1

Replace

obj[days] += value[1] + ', '

with

if (obj[days]===undefined) obj[days] = ''; 
obj[days] += value[1] + ', '

so that you don't add a string to undefined.

But instead of adding ", " after every values, you could also build an array in your loop:

if (obj[days]===undefined) obj[days] = []; 
obj[days].push(value[1])

and then use join at the end to avoid the trailing comma (and on the general principle that string building should be deferred to the rendering time).

Be careful to variable declarations: object might be OK, assuming it's defined in a just outside scope, but the missing declaration of i is very dangerous, as it's probable it's not the only i in your application.

Edit: as seen by James, you have a typo, it's either "object" or "obj".

Sign up to request clarification or add additional context in comments.

5 Comments

I think there's also a mismatch between object = {} and obj[days]
because otherwise you're about to throw away obj[days] as soon as the loop goes round - I think those results should be being stored in the object variable that's been defined at the start of the function
@JamesThorpe Oh, you mean there's a typo "object" vs "obj". I hadn't seen it. Yes, you're right (and I hope it's just in the question, not in the real code, just like the floating zero).
Yeah, sorry - I should have said between object = {} and obj. Unless of course obj is defined elsewhere. Given that object doesn't explicitly have var before it, who knows...!
Thank you very much it is working. Denys Séguret was right he even gave me the code which suits to my code ) object = {} was obj ={} in my code ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.