Home > Mobile >  How to create an array of objects with strings and arrays
How to create an array of objects with strings and arrays

Time:10-11

I have to create an array in the following format

var myData = [
  {
    x: "10:00",
    y: [15, 30],
  },
];

Where my code looks like

myData.push({
  x: startingHoursToPush   ":00",
  y: "["   startingHours[1]   ","   endingHours[1]   "]",
});

but the result I get is as following

x: "11:00"
y: "[15,30]"

I need to make the values for y an array instead of a string

CodePudding user response:

use either [ ]

myData.push({
  x: startingHoursToPush   ":00",
  y: [startingHours[1],endingHours[1]],
});

DEMO FIDDLE 1

OR

use array inside

myData.push({
      x: startingHoursToPush   ":00",
      y: new Array(startingHours[1],endingHours[1]),
    });

DEMO FIDDLE 2

CodePudding user response:

You are making a string instead of an array, try this instead

myData.push({
  x: startingHoursToPush   ":00",
  y: [startingHours[1], endingHours[1]],
});

CodePudding user response:

JS is wonderful. Just wrap it in [] brackets.

myData.push({
  x: startingHoursToPush   ":00",
  y: [startingHours[1] , endingHours[1] ],
});

  • Related