【发布时间】:2019-09-26 16:33:46
【问题描述】:
我正在尝试使用 lodash 过滤出嵌套的对象数组,这非常简单,但我希望避免多次调用。
我希望使用单个 lodash 调用/函数创建 2 个对象数组。查找对象属性“$isMultiAccount”(如果存在)将整个对象放入一个结果集中,如果不将其放入另一个规则集。
目前我正在使用 Lodash “has and filter” 为第一个和其他“!has” 这意味着相同的对象循环两次,因为对象相对较大,它会造成速度瓶颈
https://repl.it/repls/HomelyExpensiveTruetype
const item = {
"domains": [
{
"id": "dm11022",
"information":{
"description": "Customer",
"owner": {
"primary":{
"name": "James",
"phone": "NA"
},
"others": [
{
"$isMultiAccount": "./Yes"
}
]
}
}
},
{
"id": "dm12022",
"information":{
"description": "Customer",
"owner": {
"primary":{
"name": "James",
"phone": "NA"
},
"others": [
{
"$isMultiAccount": "./No"
}
]
}
}
},
{
"id": "dm12022",
"information":{
"description": "Customer",
"owner": {
"primary":{
"name": "James",
"phone": "NA"
},
"others": [
{
"conf": {
"isVpnBased":{
"accountType": "Primary"
}
}
}
]
}
}
}
]
}
/*
Expected result
output1 = [
{
"id": "dm11022",
"information":{
"description": "Customer",
"owner": {
"primary":{
"name": "James",
"phone": "NA"
},
"others": [
{
"$isMultiAccount": "./Yes"
}
]
}
}
},
{
"id": "dm12022",
"information":{
"description": "Customer",
"owner": {
"primary":{
"name": "James",
"phone": "NA"
},
"others": [
{
"$isMultiAccount": "./No"
}
]
}
}
}
]
// $isMultiAccount account do not exist in this object
output2 = [
{
"id": "dm12022",
"information":{
"description": "Customer",
"owner": {
"primary":{
"name": "James",
"phone": "NA"
},
"others": [
{
"conf": {
"isVpnBased":{
"accountType": "Primary"
}
}
}
]
}
}
}
]
*/
【问题讨论】:
-
并不是说这在这种情况下一定适用,但有时在使用lodash甚至构建ES5数组方法时,如果出现本质上循环两次的情况,有时您需要使用单个传统循环(或者更好,有时
reduce)
标签: javascript arrays ecmascript-6 lodash