-1

Fiddle: https://jsfiddle.net/3aq286rx/4/

I have an array which has nested arrays and objects

I wanted to label the colors like #f00 is red etc. etc.

I have a random number generator function which generates a random number from 0 to 2: getRandNUM(1)

Let's say the number is 2 I want to be able to pull #0f0 from my arrays without having to use .green because I wouldnt know the label based on the random number.

How can I do that

script:

var defaults = {
 backgroundcolor: '#000',
 color: '#fff',
 weekdays: ['sun','mon','tue','wed','thu','fri','sat'],
 colors: [
    {
    red: [
      "#f00"
      ]
  },
  {
    blue: [
      "#00f"
      ]
  },
  {
    green: [
      "#0f0"
      ]
  }
 ]
};

alert(defaults.colors[0].red);
Si8
  • 9,141
  • 22
  • 109
  • 221

2 Answers2

1

Instead of colors being an array of objects, where the only key is the name of the color and the value is an array with a single string of the hex code, make colors an array of objects, each with a color, and name. You can then generate your random number and use it to pick out the object in colors. Then you can use .color or .name to get the value you desire.

var defaults = {
  backgroundcolor: '#000',
  color: '#fff',
  weekdays: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
  colors: [{
      color: "#f00",
      name: "red"
    },
    {
      color: "#00f",
      name: "blue"
    },
    {
      color: "#0f0",
      name: "green"
    }
  ]
};

// however you generate your random number
var randomNumber = 2;

alert(defaults.colors[randomNumber].color);
Si8
  • 9,141
  • 22
  • 109
  • 221
larz
  • 5,724
  • 2
  • 11
  • 20
  • This could work for me as I am looking to add more complex objects so changing the format is best... Thank you – Si8 Sep 06 '18 at 18:35
1

Structure your object as follows (https://jsfiddle.net/3aq286rx/14/):

var defaults = {
 backgroundcolor: '#000',
 color: '#fff',
 weekdays: ['sun','mon','tue','wed','thu','fri','sat'],
 colors: 
    {
    red: "#f00",      
    blue: "#00f",
    green: "#0f0"
    }
};

then use Object.keys:

alert(defaults.colors.red);
alert(defaults.colors[Object.keys(defaults.colors)[0]]);

where [0] is your random number

combatc2
  • 1,215
  • 10
  • 10