我正在尝试使用reduce循环对象以生成html列表
const dropdownTemplate = (data) => {
console.log(data); // always empty
return `
<li class="dropdown__item" data-value="${data.value}"><span class="dropdown__itemCode">${data.code}</span> <span class="dropdown__itemText">${data.name}</span></li>
`;
};
const data_obj = JSON.parse('[ { "type": "hotel", "value": 25, "name":"Hotel name", "code": "sn", "lat" : "1.3", "long" : "1.33" } ]');
const fetched_items = data_obj.reduce((item, generated) => {
generated += dropdownTemplate(item);
return generated;
}, '');
console.log(fetched_items); // allways filled with undefined values
但无法理解为什么该项始终为空(因此它生成具有未定义值的列表),
我做错了什么?
答案 0 :(得分:5)
我认为你倒置了item
和generated
。
generated
是从一个循环到另一个循环的元素;和item
在实际循环中处理的数组元素。
const dataObj = JSON.parse('[ { "value": 25, "name":"Hotel name", "code": "sn" }, { "value": 30, "name2":"Hotel name2", "code": "sn2" } ]');
const dropdownTemplate = data => `<li class="dropdown__item" data-value="${data.value}"><span class="dropdown__itemCode">${data.code}</span> <span class="dropdown__itemText">${data.name}</span></li>\n\n`;
const fetchedItems = dataObj.reduce((tmp, x) => `${tmp}${dropdownTemplate(x)}`, '');
console.log(fetchedItems);
&#13;
答案 1 :(得分:-2)
理想情况下,您应该将地图用于此类场景。
减少参数就像这样(聚合,项目)=&gt; {}
const dropdownTemplate = (data) => {
return `
<li class="dropdown__item" data-value="${data.value}">
<span class="dropdown__itemCode">${data.code}</span> <span class="dropdown__itemText">${data.name}</span>
</li>`;
};
const data_obj = JSON.parse('[ { "type": "hotel", "value": 25, "name":"Hotel
name", "code": "sn", "lat" : "1.3", "long" : "1.33" } ]');
const fetched_items = data_obj.reduce((combinedHtml, item) => {
combinedHtml += dropdownTemplate(item);
return combinedHtml;
}, '');
console.log(fetched_items);