我试图在javascript数组中返回一个唯一的键值名称列表。我只能指定数组索引,但我想返回整个数组中的所有类别名称。我一直都没有定义。
这就是我的尝试:
var Foods = {
"Fruits": [
{
"id": "1",
"Name": "Granny Smith",
"Category": "Apple"},
{
"id": "2",
"Name":"Raspberries",
"Category": "Berries"}
],
"Potatoes": [
{
"id": "3",
"Name":"Maris Piper",
"Category": "White"}
{
"id": "4",
"Name":"Charlotte",
"Category": "Baby"}
]}
for(var categories in Foods) {
var cats = Foods[categories][1].Category;
document.write(cats);
}
理想情况下,我希望能够返回:
苹果 浆果 宝宝 白
任何帮助表示感谢。
干杯
答案 0 :(得分:1)
您有category
,而Category
(编辑前)
您也可以使用reduce
和Object.keys
var cats = Object.keys(Foods).reduce((prev, next) => {
prev = prev.concat(Foods[next].map(v => v.Category));
return prev;
}, [])
答案 1 :(得分:1)
您可以在for...in
循环中实现for (let item in Foods) {
Foods[item].forEach(v => console.log(v.Category));
}
功能。然后将其保存在例如数组或基本上记录它。
var Foods = {
"Fruits": [{
"id": "1",
"Name": "Granny Smith",
"Category": "Apple"
},
{
"id": "2",
"Name": "Raspberries",
"Category": "Berries"
}
],
"Potatoes": [{
"id": "3",
"Name": "Maris Piper",
"Category": "White"
}, {
"id": "4",
"Name": "Charlotte",
"Category": "Baby"
}]
}, names = [];
for (let item in Foods) {
Foods[item].forEach(v => names.push(v.Category));
}
console.log(names);
段:
$(".comp-search").typeahead({
hint: true,
highlight: true,
minLength: 1,
displayKey: 'company_name',
}, {
source: engine.ttAdapter(),
templates: {
empty: ['<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'],
header: ['<div class="list-group search-results-dropdown">'],
suggestion: function (data) {
return '<a href="javascript:void(0);" class="list-group-item">' + data.company_name + '</a>';
}
},
display: function(data) { return data.company_name; }
});
&#13;