[英]Getting boolean value from object in array then assigning it a DOM property
For example:例如:
{
"data": [
{
"name": "grape",
"fruit": false
},
{
"name": "orange",
"fruit": true
}
]
}
I am looping through the array and putting them on the DOM with this:我正在遍历数组并将它们放在 DOM 上:
for (var i=0; i < data.length; i++) {
var item = '<li>'+data[i].name+'</li>';
$('#list').append(item)
}
What I want to do is for every object in the array with the fruit
value set to true
, put is a fruit
in the DOM, and vice versa.我想要做的是将fruit
值设置为true
的数组中的每个对象,放入 DOM 中is a fruit
,反之亦然。
How can I do this?我怎样才能做到这一点?
There are many ways of doing this but basically this is the gist of it:有很多方法可以做到这一点,但基本上这是它的要点:
// Initializing the data const data = { data: [{ "name": "grape", "fruit": false }, { "name": "orange", "fruit": true } ] } // Getting the ul element const ul = document.getElementById("list") // Looping through the data array data.data.forEach((item) => { // creating the listItem and assigning the text node const listItem = document.createElement('li') item.fruit ? listItem.appendChild(document.createTextNode("The fruit " + item.name + " is a fruit")) : listItem.appendChild(document.createTextNode("The fruit " + item.name + " is not a fruit")); ul.appendChild(listItem) })
<div> <h1> Fruit checker </h1> <ul id="list"></ul> </div>
data.forEach(function(element){
var item = '<li>'+ element.name + (element.fruit ? ' is a fruit' : '') +'</li>';
$('#list').append(item);
})
You can use a ternary to add the optional text if the value is true.如果值为 true,您可以使用三元组添加可选文本。
for (var i=0; i < data.length; i++) {
var fruitBool = data.fruit ? " is a fruit" : " is not a fruit";
var item = '<li>' + data[i].name + fruitBool + '</li>';
$('#list').append(item)
}
You can use template literals.您可以使用模板文字。 Secondly to access data
you need to first access the object.其次要访问data
您需要首先访问对象。
let obj = { "data": [{ "name": "grape", "fruit": false }, { "name": "orange", "fruit": true } ] } let str = ''; let dt = obj.data; for (var i = 0; i < dt.length; i++) { str += `<li>${dt[i].name}</li>` } document.getElementById('list').innerHTML = str
<ul id='list'></ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.