我正在学习javascript,这可能是一个基本问题,请帮我实现以下目标。
我正在构建一个像obejct一样的数组,以便稍后使用数据。现在,我必须将类别作为“帮助”发送,并且需要动态获取所有子类别值。
[
{"category":"Help","subcategory":"Email"},
{"category":"Help","subcategory":"application"},
{"category":"Help","subcategory":"Software"},
{"category":"Help","subcategory":"Hardware"},
{"category":"Request","subcategory":"Access"},
{"category":"Request","subcategory":"Remote"},
]
提前致谢
答案 0 :(得分:3)
您可以先使用Array#filter
进行过滤,然后使用Array#map
获取值。
var array = [{ category: "Help", subcategory: "Email" }, { category: "Help", subcategory: "application" }, { category: "Help", subcategory: "Software" }, { category: "Help", subcategory: "Hardware" }, { category: "Request", subcategory: "Access" }, { category: "Request", subcategory: "Remote" }],
subcategory = array
.filter(a => a.category === 'Help')
.map(a => a.subcategory);
console.log(subcategory);

.as-console-wrapper { max-height: 100% !important; top: 0; }

ES5
var array = [{ category: "Help", subcategory: "Email" }, { category: "Help", subcategory: "application" }, { category: "Help", subcategory: "Software" }, { category: "Help", subcategory: "Hardware" }, { category: "Request", subcategory: "Access" }, { category: "Request", subcategory: "Remote" }],
subcategory = array
.filter(function (a) { return a.category === 'Help'; })
.map(function (a) { return a.subcategory; });
console.log(subcategory);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)
您应该使用filter
方法来实现此目的。
另外,使用map
方法只能使用subcategories
创建新数组。
var array=[
{"category":"Help","subcategory":"Email"},
{"category":"Help","subcategory":"application"},
{"category":"Help","subcategory":"Software"},
{"category":"Help","subcategory":"Hardware"},
{"category":"Request","subcategory":"Access"},
{"category":"Request","subcategory":"Remote"},
];
var subcategories = array.filter(a => a.category === "Help").map(a => a.subcategory);
console.log(subcategories);

.as-console-wrapper { max-height: 100% !important; top: 0; }