c.chester
c.chester

Reputation: 11

console.log returns [object Object]

I'm starting with javascript and I have this problem I'm trying to return and array with the data but when I console log I get "[object Object][object Object]"

this is the data I have to work with

var MARKDATA = {
 "SOR": {
   "mark": [
    {
     "data": {
       "2015": 21.680000,
       "2016": 23.739999,
       "2017": 23.760000
     },
     "markName": "swimming",
     "markCode": "SWM"
   },
   {
    "data": {
       "2015": "",
       "2016": 61.55429840,
       "2017": 61.482299804
     },
     "markName": "running (time)",
     "indicatorCode": "RM"
   }
  ]
 } 
};

this is what I tried

const valuesArr= MARKDATA.SOR.mark;

let acum= '';
const showData = arr => {
 const dataArr= arr.map(value => value.data).join('') 
 acum += dataArr;
};
showData(valuesArr);

console.log(acum)

I want that console log returns and array with the years and the values of the object data, what I want to do is use this array to calculate with the reduce method the average of each data.

Or if someone knows a better way to get the average of the values of the object data I will apreciate it

Upvotes: 0

Views: 2274

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073959

Your current code is building a string, explicitly:

  • You initialize acum with a string ('')
  • You call join('') (which creates a string) on the result of the map operation

Since map is creating an array of objects, calling join on taht array implicitly calls toString on those objects. An object that doesn't have special toString behavior returns "[object Object]" in that case.

If you want an array of the data contents, you need to work at the array level:

let acum = []; // <== An array
const showData = arr => {
    const dataArr= arr.map(value => value.data); // <== No join('')
    acum.push(...dataArr); // <== Appending to the array
};
showData(valuesArr);

console.log(acum);

That's the minimal changes version, but there's no reason to create those temporary arrays (the return values of map), and there's no reason for the showData function. Just use a for-of loop. You can also include destructuring. So:

let acum = [];
for (const {data} of valuesArr) {
    acum.push(...data);
}

console.log(acum);

You can shoehorn that into a reduce (because you can shoehorn any array operation into a reduce), but it doesn't buy you anything:

let acum = valuesArr.reduce((a, {data}) => {
    a.push(...data);
    return a;
}, []);

console.log(acum);

Alternately (but this still pointlessly creates an extra array) you could use the proposed-but-still-Stage-3 Array.prototype.flat:

let acum = valueArr.map(({data}) => data).flat();

console.log(acum);

Upvotes: 2

Related Questions