将特定的JSON数组存储在变量中

Bri*_*ian 5 javascript json loops firebase firebase-realtime-database

我有一个像这样的JSON对象:

{
  "workouts":
  [
    {
      "title": "Full Body",
      "exercises":
      [
        {
          "name": "Push Ups",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Squats",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Running in Place",
          "duration": 3,
          "break": 3
        }
      ]
    },
    {
      "title": "God Legs",
      "exercises":
      [
        {
          "name": "Running in Place (High Knees)",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Squats",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Clams",
          "duration": 3,
          "break": 3
        }
      ]
    },
    {
      "title": "Morning Stretch",
      "exercises":
      [
        {
          "name": "Downward Dog",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Face Plant",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Warrior",
          "duration": 3,
          "break": 3
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我正在循环这个对象,并创建包含每个锻炼的标题的信息卡("全身","上帝腿"等).

点击其中一张牌后,我希望能够将与每个标题相关的练习存储到变量中以供进一步使用.例如,如果我点击"God Legs",我希望变量存储:"[{'name':'Running in Place (High Knees)', 'duration':3, 'break':3},{'name':'Squats', 'duration':3, 'break':3},{'name': 'Clams', 'duration':3, 'break':3}]"

这是我用来循环遍历JSON数据的代码,该数据存储在Firebase实时数据库中,并创建信息卡.

JavaScript的:

// Initialize Firebase.
firebase.initializeApp(config);
// Reference data.
var dbRef = firebase.database().ref().child("workouts");
// Sync with Firebase in real time.
dbRef.on("value", snap =>
{

  var workouts = snap.val();

  for (var i = 0;  i < workouts.length; i++)
  {
    //display.innerHTML = exercises[0].name;
    var routine = workouts[i].title;
    var id = "card" + i;

    var $card = ("<li><div class='card' id=" + id + "><a class='startIt' href='timer.html'>\n\
    <div class='cardInfo'><h3>" + routine + "</h3><p>10 min.</p>\n\
    </div></a><a class='cardOptions' href='overview.html'>\n\
    </a></div></li>");

    $("#cardList").append($card);
  }
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<ul id="cardList" class="cards"></ul>
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助和想法!

Rom*_*man 1

您可以使用find

相关代码

workouts.find(workout => workout.title === [insert title you are looking for])
Run Code Online (Sandbox Code Playgroud)

例子

workouts.find(workout => workout.title === [insert title you are looking for])
Run Code Online (Sandbox Code Playgroud)
const json = {
  "workouts": [{
      "title": "Full Body",
      "exercises": [{
          "name": "Push Ups",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Squats",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Running in Place",
          "duration": 3,
          "break": 3
        }
      ]
    },
    {
      "title": "God Legs",
      "exercises": [{
          "name": "Running in Place (High Knees)",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Squats",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Clams",
          "duration": 3,
          "break": 3
        }
      ]
    },
    {
      "title": "Morning Stretch",
      "exercises": [{
          "name": "Downward Dog",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Face Plant",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Warrior",
          "duration": 3,
          "break": 3
        }
      ]
    }
  ]
}

function createButton(value) {
  const button = document.createElement('button')
  button.textContent = value
  return button
}

function append(parentQuery, childNode) {
  document.querySelector(parentQuery).append(childNode)
}

// log the right object on click
function handleButtonClick(event) {
  if (event.target != event.currentTarget) {
    console.log(json.workouts.find(workout => workout.title === event.target.textContent))
  }
}

// display the buttons
json.workouts.forEach(workout => append('#workout_section', createButton(workout.title)))

// eventlistener
document.querySelector('#workout_section').addEventListener('click', handleButtonClick)
Run Code Online (Sandbox Code Playgroud)

编辑 - 按 HTML 属性搜索

您可以添加 HTML 元素自定义属性,例如data-workout. 现在您可以find通过该属性搜索来使用。

// add attribute
button.setAttribute('data-workout', value)

// find attribute
json.workouts.find(workout => workout.title === event.target.dataset.workout)
Run Code Online (Sandbox Code Playgroud)

<section id="workout_section"></section>
Run Code Online (Sandbox Code Playgroud)
// add attribute
button.setAttribute('data-workout', value)

// find attribute
json.workouts.find(workout => workout.title === event.target.dataset.workout)
Run Code Online (Sandbox Code Playgroud)

编辑-for循环

我添加data-workout="${routine}"div

<li>
    <div class="card" id="${id}" data-workout="${routine}">`
    [...]
</li>
Run Code Online (Sandbox Code Playgroud)

并在每张卡上添加事件监听器

$(".card").on('click', handleButtonClick)
Run Code Online (Sandbox Code Playgroud)

const json = {
  "workouts": [{
      "title": "Full Body",
      "exercises": [{
          "name": "Push Ups",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Squats",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Running in Place",
          "duration": 3,
          "break": 3
        }
      ]
    },
    {
      "title": "God Legs",
      "exercises": [{
          "name": "Running in Place (High Knees)",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Squats",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Clams",
          "duration": 3,
          "break": 3
        }
      ]
    },
    {
      "title": "Morning Stretch",
      "exercises": [{
          "name": "Downward Dog",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Face Plant",
          "duration": 3,
          "break": 3
        },
        {
          "name": "Warrior",
          "duration": 3,
          "break": 3
        }
      ]
    }
  ]
}

function createButton(value) {
  const button = document.createElement('button')
  button.textContent = value
  button.setAttribute('data-workout', value)
  return button
}

function append(parentQuery, childNode) {
  document.querySelector(parentQuery).append(childNode)
}

// log the right object on click
function handleButtonClick(event) {
  if (event.target != event.currentTarget) {
    console.log(json.workouts.find(workout => workout.title === event.target.dataset.workout))
  }
}

// display the buttons
json.workouts.forEach(workout => append('#workout_section', createButton(workout.title)))

// eventlistener
document.querySelector('#workout_section').addEventListener('click', handleButtonClick)
Run Code Online (Sandbox Code Playgroud)
<section id="workout_section"></section>
Run Code Online (Sandbox Code Playgroud)