我真的很喜欢vanilla JavaScript,所以请耐心等待。
所以我有一个对象数组,如下所示:
var partyGuests =[
{
firstName: "Wayne",
lastName: "Gretzky",
items: "birthday cake"
},
{
firstName: "Emily",
lastName: "Janeson",
items: "balloons"
},
{
firstName: "Gordon",
lastName: "Ramsey",
items: "balloons"
},
{
firstName: "Jasmine",
lastName: "Quaker",
items: "birthday cake"
}
]
如果他们带来“气球”,他们将附加到<div id="balloonGroup">
,如果他们带来“生日蛋糕”,他们将附加到<div id="cakeGroup">
我希望我的整个对象数组显示在页面上(包括名称,姓氏和项目),但是根据它们带来的项目显示在div中。
我已经尝试过使用map,forEach和filter,但我不确定我做错了什么。
这是我尝试过的,但我无法找到一种方法将它们分类到适当的div中。
let guests = partyGuests.map(res=>{
return res;
})
function groupAssignment(value, index){
const FirstName = `<li>Name: ${value.firstName}</li>`;
const LastName = `<li> Last Name: ${value.lastName}</li>`;
const Item = `<li>Item: ${value.item}</li>`;
$("#1").append(firstName, lastName, Item);
}
guests.forEach(groupAssignment);
你只需要简单地循环遍历数组并填充div
内的相应id
内容:
var partyGuests =[
{
firstName: "Wayne",
lastName: "Gretzky",
items: "birthday cake"
},
{
firstName: "Emily",
lastName: "Janeson",
items: "balloons"
},
{
firstName: "Gordon",
lastName: "Ramsey",
items: "balloons"
},
{
firstName: "Jasmine",
lastName: "Quaker",
items: "birthday cake"
}
];
partyGuests.forEach((obj)=>{
if(obj.items === 'balloons'){
$('#balloonGroup').append(
obj.firstName + ' ' + obj.lastName + ' '
+ obj.items + '<br>'
);
}
if(obj.items === 'birthday cake'){
$('#cakeGroup').append(
obj.firstName + ' ' + obj.lastName + ' '
+ obj.items + '<br>'
);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="balloonGroup"></div>
<div id="cakeGroup"></div>
您应该在代码中使用.forEach
,因为您只需要迭代所有数组元素。
这里采取的步骤是:
items
值获取要追加的选择器。.append()
将html字符串附加到选择器var partyGuests = [{
firstName: "Wayne",
lastName: "Gretzky",
items: "birthday cake"
},
{
firstName: "Emily",
lastName: "Janeson",
items: "balloons"
},
{
firstName: "Gordon",
lastName: "Ramsey",
items: "balloons"
},
{
firstName: "Jasmine",
lastName: "Quaker",
items: "birthday cake"
}
];
partyGuests.forEach(
el => {
var _html = '<p><strong>First Name:</strong>' + el.firstName + '<br>' +
'<strong>Last Name:</strong>' + el.lastName + '<br>' +
'<strong>Items:</strong>' + el.items + '<br></p>';
var elem = "";
if (el.items === "birthday cake")
elem = '#cakeGroup';
else if (el.items === "balloons")
elem = '#balloonGroup';
$(elem).append(_html);
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="balloonGroup">
<h3>Balloons</h3>
</div>
<div id="cakeGroup">
<h3>Cakes</h3>
</div>
for(var i=0; i<partyGuests.length; i++){
if (partyGuests[i].items == "birthday cake") {
//append to cakeGroup here
} else if (partyGuests[i].items == "balloons") {
//append to balloonGroup
}
}
循环遍历guest数组并检查items属性