javascript - 使用 array.map() 提取 JSON 值

标签 javascript

我尝试使用以下代码从 JSON 对象中提取特定值:

 data: any[] = [
    {'id': 1, 'expenseType': {'id': 1, 'name': 'type1'} , 'cost': 100},
    {'id': 2, 'expenseType': {'id': 2, 'name': 'type2'}, 'cost': 200 },
    {'id': 3, 'expenseType': {'id': 3, 'name': 'type3'}, 'cost': 300} }
];

 filterData = this.data.map(({ expenseType }) => ({
   expenseType   
 }));

我想要filterData是一个数组:

[{'id': 1, 'name': 'type1'},{'id': 2, 'name': 'type2'}, {'id': 3, 'name': 'type3']

问题是 key 也包含在内。

我可以使用array.map()来实现这一点吗? ?

最佳答案

您只需返回expenseType,而不将其用作 short hand property .

var data = [{ id: 1, expenseType: { id: 1, name: 'type1' }, cost: 100  }, { id: 2, expenseType: { id: 2, name: 'type2' }, cost: 200 }, { id: 3, expenseType: { id: 3,  name: 'type3' }, cost: 300 }],
    filterData = data.map(({ expenseType }) => expenseType);

console.log(filterData);

关于javascript - 使用 array.map() 提取 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60146710/

相关文章:

javascript - 限定由多个异步回调共享的变量

javascript - SimulatedGreg Electron-Vue-Vuetify错误消息: [Vue warn]: Unknown custom element: <v-app> - did you register the component correctly?

javascript - Chrome 扩展程序/网络应用程序 session 控制

javascript - 根据字符串获取永久数组项

javascript - 如何在按钮单击事件上显示 typeahead.js 下拉数据?

javascript - .click() 在没有点击时有时会被调用

php - JavaScript 来更新 MySQL?

javascript - 如果在 asp.net 中隐藏了另一个按钮,则单击按钮时显示弹出窗口

javascript - 如何将 PHP smarty 模板与 Vue.js 集成?

javascript - 类型错误:传递给 Illuminate\Database\Grammar::parameterize() 的参数 1 必须是数组类型,给定字符串