gpt4 book ai didi

javascript - 使用javascript从下面的对象中获取键值对

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:54 24 4
gpt4 key购买 nike

我正在学习 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"},
]

提前致谢

最佳答案

您可以使用 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; }

关于javascript - 使用javascript从下面的对象中获取键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43492846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com