Использовать переменную в качестве исходного массива на карте - PullRequest
0 голосов
/ 17 января 2020

Моя цель - чтобы пользователь щелкнул по дате, и карта США изменится, чтобы использовать новый массив данных, основанный на выбранном году.

// When user clicks on li under years
  $('#years').children('li').click(function(){

    // Get last two characters of id and prepend y
    let id = 'y' + this.id.slice(-2);

    // Output is y04
    console.log(id);

    // Use id variable to get array for that year, then pass through getColour function.
    let newArray = $.map(id, function(item) { 
        return getColour("#e67d73", "#57bb8a", 16, 100, item) 
    });

    // step through states array and apply the colour value from newArray to each state
    states.forEach((state, index) => {
      const colour = newArray[index];
      $(state).css('fill', colour);
    });
  });

Для начальной загрузки карты я с помощью. Это прекрасно работает:

//Use y04 array for getColour function
let initialArray = y04.map(function(item) {
    return getColour("#e67d73", "#57bb8a", 16, 100, item)
});

Я провел различные тесты с использованием let newArray = id.map(//more code), но из моих исследований переменная id должна быть объектом, а не строкой.

Как я могу преобразовать мою id строку в объект, который .map может использовать? Можно ли передать переменную в качестве исходного массива в .map?

1 Ответ

3 голосов
/ 17 января 2020

Предполагая, что у вас есть массив для каждого года, чтобы затем использовать значение в качестве переменной, вам нужно изменить свой подход. Вам необходимо создать структуру данных объекта, где каждое свойство будет представлять значение, которое вы получите, которое будет связано с массивом. Примерно так:

// created a mapper data structure
var mapper = {
  y01: [1, 2, 3], // array y01 will be here
  y02: [1, 2, 3], // array y02 will be here
  y03: [1, 2, 3], // array y03 will be here
  y04: [1, 2, 3], // array y04 will be here
  .
  .
  .
};

// when you do the initial call
//Use y04 array for getColour function
let initialArray = mapper['y04'].map(function(item) {
  return getColour("#e67d73", "#57bb8a", 16, 100, item)
});


//inside the code
// When user clicks on li under years
$('#years').children('li').click(function() {

  // Get last two characters of id and prepend y
  let id = 'y' + this.id.slice(-2);

  // Output is y04
  console.log(id);

  // Use mapper to get the array using the id value
  let newArray = $.map(mapper[id], function(item) {
    return getColour("#e67d73", "#57bb8a", 16, 100, item)
  });

  // step through states array and apply the colour value from newArray to each state
  states.forEach((state, index) => {
    const colour = newArray[index];
    $(state).css('fill', colour);
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...