[
{
"id":100,
"account_id":8,
"name":"Out of Service",
"default":false,
"created_at":"2012-02-06T08:51:29.720-06:00",
"updated_at":"2012-02-06T08:51:29.720-06:00"
},
...
]
这是我的示例对象。我从一个url获取应用程序请求中得到这个。我如何过滤它,这样我就可以发布一个只有一种类型的值的列表。
例如:如果我想过滤它的密钥Id,我想得到一个列表,类似于:100101,。。。等等。
感谢
您应该使用Array.prototype.map((而不是Array.prototype.filter()
代码:
const data = [
{
"id":100,
"account_id":8,
"name":"Out of Service",
"default":false,
"created_at":"2012-02-06T08:51:29.720-06:00",
"updated_at":"2012-02-06T08:51:29.720-06:00"
},
{
"id":101,
"account_id":8,
"name":"Out of Service",
"default":false,
"created_at":"2012-02-06T08:51:29.720-06:00",
"updated_at":"2012-02-06T08:51:29.720-06:00"
},
]
const result = data.map(obj => obj.id)
console.log(result)
对于谷歌应用程序,脚本箭头函数(=>
(不起作用。
用途:
function testIt()
{
var sample = [
{
"id":100,
"account_id":8,
"name":"Out of Service",
"default":false,
"created_at":"2012-02-06T08:51:29.720-06:00",
"updated_at":"2012-02-06T08:51:29.720-06:00"
},
{
"id":101,
"account_id":8,
"name":"Out of Service",
"default":false,
"created_at":"2012-02-06T08:51:29.720-06:00",
"updated_at":"2012-02-06T08:51:29.720-06:00"
},
];
var result = sample.map(function(elt) { return elt.id; });
Logger.log(result); // [100.0, 101.0]
}
您也可以使用Array.reduce,尽管我不确定Yosvel的映射方法是否有任何好处:
const data = [
{
"id":100,
"account_id":8,
"name":"Out of Service",
"default":false,
"created_at":"2012-02-06T08:51:29.720-06:00",
"updated_at":"2012-02-06T08:51:29.720-06:00"
},
{
"id":102,
"account_id":8,
"name":"Out of Service",
"default":false,
"created_at":"2012-02-06T08:51:29.720-06:00",
"updated_at":"2012-02-06T08:51:29.720-06:00"
},
{
"id":105,
"account_id":8,
"name":"Out of Service",
"default":false,
"created_at":"2012-02-06T08:51:29.720-06:00",
"updated_at":"2012-02-06T08:51:29.720-06:00"
},
]
const res = data.reduce(
(acc, val) => {
return [...acc, val.id]
},
[]
)
console.log(res)
const extractFieldArray = (data, key) => data.map(d => d[key]);
//data
是您的对象,key
是您想要提取的内容,就像id
一样