object

Javascript Object.values


I have an object with years and it's values

const years = {};
rows.forEach(row => {
  const cols = row.split(';');
  years[cols[0]] += cols[3];
});

This part works fine.

I want to exctracts the values. I tried this:

Object.values(years),

But it doesn't work. Maybe the values are not set correct.


Solution

  • Basically you need an object

    years = {}
    

    and later with a default value for not initialised value and a numerical value for adding.

    years[cols[0]] = (years[cols[0]] || 0) + +cols[3];
    

    const
        data = 'xyz\n2006;7;1;20;0\n2006;8;1;40;1\n2007;1;1;30;0\n2007;6;1;60;0',
        years = {},
        rows = data.split('\n').slice(1); //It's simple csv text file
    
    rows.forEach(row => {
        const cols = row.split(';');
        years[cols[0]] = (years[cols[0]] || 0) + +cols[3];
    });
    
    console.log(Object.keys(years));
    console.log(Object.values(years));