1

How can I use map function to have 3 arrays under datasets instead of another object called 'label'. When I try to put map function before 'label', just after 'dataset' in constructor function I am getting weird errors about having unexpected '.' dots etc.

Expected output

{
  colors: blue,
  datasets: [
    {
      label: 'car',
      type: 'line',
      data: '1'
    },
    {
      label: 'bus',
      type: 'line',
      data: '5'
    },
    {
      label: 'train',
      type: 'line',
      data: '10'
    }
  ]
}

function Constructor(colors, label, type, data) {
  this.colors = colors;
  this.label = label;
  this.type = type;
  this.data = data;

  this.mainData = {
    colors: colors,
    datasets: [{
      label: label.map((label, i) => ({
        type: type,
        data: data[i]
      }))
    }]
  }
};

var whyYouNoWork = new Constructor('blue', ['car', 'bus', 'train'], 'line', ['1', '5', '10']);

console.log(whyYouNoWork.mainData);

1 Answer 1

2

You can use the function map to build the desired output:

function Constructor(colors, label, type, data) {
  this.colors = colors;
  this.label = label;
  this.type = type;
  this.data = data;

  this.mainData = { colors, datasets: label.map((label, i) => ( { label, type, data: data[i] } ) ) }
};

var whyYouNoWork = new Constructor('blue', ['car', 'bus', 'train'], 'line', ['1', '5', '10']);

console.log(whyYouNoWork.mainData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

why do I have to get rid of [{ after datasets: ?

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.