1

So I have an array object variable with this structure

var array_obj = [
   {
      Gooble: 240,
      year: 2018
   },
   {
      Koolle: 220,
      year: 2018
   }
    {
      Zooae: 220,
      year: 2015
   }
];

But I want to follow this structure instead https://www.amcharts.com/demos/stacked-column-chart

So now it should be

    var array_obj = [
       {
          Gooble: 240,
          Koolle: 220,
          year: 2018
       },
       {
          Zooae: 220,
          year: 2015
       }
    ];

I've been trying to this with this loop but I can't seem to do it properly.

for(var i in array_obj){
   if(array_obj[i].year == array_obj[i].year){
      # Push here
   }
}
2
  • The proposed structure should probably be more like [{ year: 2018, entries: [{ name: 'Zooae', value: 220 }, ...] }, ...] or similar? Commented Oct 10, 2018 at 2:14
  • @Marty I'm following this structure from this chart amcharts.com/demos/stacked-column-chart Commented Oct 10, 2018 at 2:31

2 Answers 2

1

Another solution is to build an object with year as keys and combined data as values:

var array_obj = [{
    Gooble: 240,
    year: 2018
  },
  {
    Koolle: 220,
    year: 2018
  },
  {
    Zooae: 220,
    year: 2015
  }
];

let yearBuckets = {};
array_obj.forEach(b => {
  if (b.year in yearBuckets) Object.assign(yearBuckets[b.year], b);
  else yearBuckets[b.year] = b;
});
console.log(Object.values(yearBuckets));

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

Comments

1

Use reduce to create an object of objects indexed by year, creating the subobject first if it doesn't exist, and then iterate over the non-year properties and assigning to the appropriate key on the subobject.

Also make sure to correct your input array_obj - all array items need to be separated with commas for the syntax to be valid:

var array_obj = [
   {
      Gooble: 240,
      year: 2018
   },
   {
      Koolle: 220,
      year: 2018
   },
    {
      Zooae: 220,
      year: 2015
   }
];
const outputByYear = array_obj.reduce((a, { year, ...rest }) => {
  if (!a[year]) a[year] = { year };
  Object.entries(rest).forEach(([key, val]) => {
    a[year][key] = val;
  });
  return a;
}, {});
console.log(Object.values(outputByYear));

1 Comment

I'll try this. Thank you.

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.