*注意:我正在寻找Vanilla JS(没有jQuery)的解决方案,最好不是for循环。
我有一个简单的JSON数据集,我想在其中将每个“类型”推入字符串数组中。
[
{
"type": "Fruits",
"objects":
[
{"name": "Apples", "qty":35},
{"name": "Bananas", "qty":48},
{"name": "Oranges", "qty":12}
]
},
{
"type": "Vegetables",
"objects":
[
{"name": "Celery", "qty":255},
{"name": "Potatos", "qty":105},
{"name": "Carrots", "qty":483},
{"name": "Peas", "qty":350}
]
},
{
"type": "Meats",
"objects":
[
{"name": "Lamb", "qty":255},
{"name": "Chicken", "qty":545},
{"name": "Beef", "qty":13}
]
}
]
输出应为:
["Fruits", "Vegetables", "Meats"]
我将JSON对象解析为一个变量(有效),但是
我不明白为什么简单的filter
函数不起作用:
var myData = require("../data.json");
console.log(myData); // <-- Yay! I have my data
//Retrieve all "type" strings into an array (** this isn't working **)
var myTypes = myData.filter(a => a.type);
console.log(myTypes); // <-- This shows an array of objects (like above) and not an array of string "type"
答案 0 :(得分:3)
您可以使用map
代替filter
const items = [
{
"type": "Fruits",
"objects":
[
{"name": "Apples", "qty":35},
{"name": "Bananas", "qty":48},
{"name": "Oranges", "qty":12}
]
},
{
"type": "Vegetables",
"objects":
[
{"name": "Celery", "qty":255},
{"name": "Potatos", "qty":105},
{"name": "Carrots", "qty":483},
{"name": "Peas", "qty":350}
]
},
{
"type": "Meats",
"objects":
[
{"name": "Lamb", "qty":255},
{"name": "Chicken", "qty":545},
{"name": "Beef", "qty":13}
]
}
]
const types = items.map(item => item.type)
console.log(types)
// [ 'Fruits', 'Vegetables', 'Meats' ]
答案 1 :(得分:1)
您应该使用map
而不是filter
:
var data = [
{
"type": "Fruits",
"objects":
[
{"name": "Apples", "qty":35},
{"name": "Bananas", "qty":48},
{"name": "Oranges", "qty":12}
]
},
{
"type": "Vegetables",
"objects":
[
{"name": "Celery", "qty":255},
{"name": "Potatos", "qty":105},
{"name": "Carrots", "qty":483},
{"name": "Peas", "qty":350}
]
},
{
"type": "Meats",
"objects":
[
{"name": "Lamb", "qty":255},
{"name": "Chicken", "qty":545},
{"name": "Beef", "qty":13}
]
}
]
console.log(data.map((obj) => obj.type))
答案 2 :(得分:1)
使用map函数。
console.log(array.map(a => a.type));