我使用Javascript尝试从JSON对象创建一个数组。问题是我正在尝试获取一个数组的acceptedAnswers。我认为地图是最好的功能。但是,返回的是一个数组数组。我只想获取值数组。感谢您的帮助。
代码
let categories = [
{
"categoryID": "1",
"categoryName": "Fruits with seeds",
"acceptedAnswers": [
"2","5"
]
},
{
"categoryID": "2",
"categoryName": "Fruits without seeds",
"acceptedAnswers": [
"1","3","4"
]
},
{
"categoryID": "3",
"categoryName": "Blue Fruit",
"acceptedAnswers": [
"1"
]
}
]
JS
let catAcceptedAnswerArray = categories.map(function (cat) {
return cat.acceptedAnswers
})
console.log(catAcceptedAnswerArray)
返回:
0: ["2","5"]
1: ["1","3","4"]
2: ["1"]
我想返回:
0: ["2","5","1","3","4","1"]
这里是fiddle
答案 0 :(得分:4)
map
不是此处的正确工具。只需创建一个数组并将每个对象的条目附加到该数组即可:
const result = [];
for (const category of categories) {
result.push(...category.acceptedAnswers);
}
或者,如果您不能使用ES2015 +功能,则使用ES5版本:
var result = [];
categories.forEach(function(category) {
result.push.apply(result, category.acceptedAnswers);
});
这假设不会有成千上万的{{1}};一次acceptedAnswers
的调用具有特定于平台的限制(但同样,成千上万)。
与几乎所有数组操作一样,将它们刺入push
是可能,但您不会从中获得任何收获:
reduce
答案 1 :(得分:2)
使用ES6,您可以尝试:
categories
.map(category => category.acceptedAnswers)
.reduce((acc, ids) => acc.concat(ids), [])
答案 2 :(得分:1)
var result = categories.reduce(function(arr, category) {
arr.push.apply(arr, category.acceptedAnswers);
return arr;
}, []);