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

时间:2023-02-08 15:41:42

I have a JSON object like so:

我有一个像这样的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
        }
      ]
    }
  ]
}

I am looping through this object and creating info cards containing the title of each workout ("Full Body", "God Legs" etc).

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

Upon clicking one of the cards, I would like to be able to store the exercises associated with each title into a variable for further use. For example, If I click on "God Legs", I want the variable to store: "[{'name':'Running in Place (High Knees)', 'duration':3, 'break':3},{'name':'Squats', 'duration':3, 'break':3},{'name': 'Clams', 'duration':3, 'break':3}]"

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

Here is the code I am using to loop through the JSON data, which is stored on Firebase realtime database, and create the info cards.

这是我用来循环遍历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);
  }
});

HTML:

<ul id="cardList" class="cards"></ul>

Thanks for any help and ideas!

感谢您的帮助和想法!

1 个解决方案

#1


2  

You can use find

你可以使用find

Relevant Code

workouts.find(workout => workout.title === [insert title you are looking for])

Example

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)
<section id="workout_section"></section>

Edit - search by HTML-Attribute

You can add HTML element an custom attribute like data-workout. Now you can use find by searching by this attribute.

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

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

// find attribute
json.workouts.find(workout => workout.title === event.target.dataset.workout)

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)
<section id="workout_section"></section>

Edit - for loop

I add data-workout="${routine}" to the div

我在div中添加了data-workout =“$ {routine}”

<li>
    <div class="card" id="${id}" data-workout="${routine}">`
    [...]
</li>

and add the eventlistener on every card

并在每张卡上添加eventlistener

$(".card").on('click', handleButtonClick)

const routines = {
  "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
        }
      ]
    }
  ]
}

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

function appendElement(htmlString, parentQuery) {
  $(parentQuery).append(htmlString)
}

function createCardsHtmlString(id, routine) {
  return `
    <li>
      <div class="card" id="${id}" data-workout="${routine}">
        <a class="startIt" href="#">
          <div class="cardInfo">
            <h3>${routine}</h3>
            <p>10 min.</p>
          </div>
        </a>
        <a class="cardOptions" href="#"></a>
      </div>
    </li>
  `
}

for (var i = 0; i < routines.workouts.length; i++) {
  var routine = routines.workouts[i].title;
  var exercises = routines.workouts[i].exercises
  var id = "card" + i;
  $("#cardList").append(createCardsHtmlString(id, routine));
}

$(".card").on('click', handleButtonClick)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="cardList"></ul>

#1


2  

You can use find

你可以使用find

Relevant Code

workouts.find(workout => workout.title === [insert title you are looking for])

Example

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)
<section id="workout_section"></section>

Edit - search by HTML-Attribute

You can add HTML element an custom attribute like data-workout. Now you can use find by searching by this attribute.

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

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

// find attribute
json.workouts.find(workout => workout.title === event.target.dataset.workout)

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)
<section id="workout_section"></section>

Edit - for loop

I add data-workout="${routine}" to the div

我在div中添加了data-workout =“$ {routine}”

<li>
    <div class="card" id="${id}" data-workout="${routine}">`
    [...]
</li>

and add the eventlistener on every card

并在每张卡上添加eventlistener

$(".card").on('click', handleButtonClick)

const routines = {
  "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
        }
      ]
    }
  ]
}

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

function appendElement(htmlString, parentQuery) {
  $(parentQuery).append(htmlString)
}

function createCardsHtmlString(id, routine) {
  return `
    <li>
      <div class="card" id="${id}" data-workout="${routine}">
        <a class="startIt" href="#">
          <div class="cardInfo">
            <h3>${routine}</h3>
            <p>10 min.</p>
          </div>
        </a>
        <a class="cardOptions" href="#"></a>
      </div>
    </li>
  `
}

for (var i = 0; i < routines.workouts.length; i++) {
  var routine = routines.workouts[i].title;
  var exercises = routines.workouts[i].exercises
  var id = "card" + i;
  $("#cardList").append(createCardsHtmlString(id, routine));
}

$(".card").on('click', handleButtonClick)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="cardList"></ul>