gpt4 book ai didi

javascript - 如何从数组中删除不包含特定字符串的字段的所有元素?

转载 作者:行者123 更新时间:2023-11-28 18:10:39 29 4
gpt4 key购买 nike

这是从 ElasticSearch 查询获得的一些结果..

"buckets": [{
"key": "another_service_name:0.0.1",
"doc_count": 105,
"containers": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": "7eaf4933b0366f7212f30f9f3c315672ea18e026922d0651b29b844763be6b0a",
"doc_count": 105,
"someField": {
"value": 1.2708647376015072
}
}]
}
}, {
"key": "my_service_name:0.0.1",
"doc_count": 200,
"containers": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": "4c27931147386d49e90f581a1d5cb22f53cda00b16107864cad9eff32f61d776",
"doc_count": 100,
"someField": {
"value": 77.9621390914917
}
}, {
"key": "392e7e6981cd4c24c526ffda03977b7984ebcae58194680c82940af4acec4748",
"doc_count": 100,
"someField": {
"value": 76.63604362487793
}
}]
}
}]

是否有一个简单的 1-liner 可以从外部 buckets 数组中删除没有包含 my_service_namekey 的任何元素?

我知道我可以循环数组,使用 indexOfsplice ..但是有更短的方法吗?

我希望结果看起来像这样..

"buckets": [{
"key": "my_service_name:0.0.1",
"doc_count": 200,
"containers": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": "4c27931147386d49e90f581a1d5cb22f53cda00b16107864cad9eff32f61d776",
"doc_count": 100,
"someField": {
"value": 77.9621390914917
}
}, {
"key": "392e7e6981cd4c24c526ffda03977b7984ebcae58194680c82940af4acec4748",
"doc_count": 100,
"someField": {
"value": 76.63604362487793
}
}]
}
}]

最佳答案

您可以使用Array.prototype.filter方法:

var queryResults = /* your result as above */;

var myServices = queryResults.filter(function(element) {
return element.key.indexOf('my_service_name') >= 0;
})

在 ES6 中,可以将其缩短为:

let queryResults = /* your result as above */;

let myServices = queryResults.filter(element => element.key.includes('my_service_name'))

关于javascript - 如何从数组中删除不包含特定字符串的字段的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41676820/

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