如何在嵌套的onject中推送响应

问题描述

我有一个嵌套的数据,我试图在其中推送从服务器获得的响应,

我的数据是:

let d = [{
    "dashId": 3,"dashName": "one","dashData": []
  },{
    "dashId": 4,"dashName": "two","dashData": [{
      "nestedId": 1,"nestedData": "how are you"
    }]
  }
]

这是我要推送的数据

let res = [{
  "nestedId": 11,"nestedData": "I am fine"
}]

我正在做的是:-

let dd = d.map(li => {
  if (li.dashId === 3) {
    li.dashData.push(res)
  }
})

console.log(dd)

我得到的输出未定义

[ undefined,undefined ]

解决方法

Array.map函数创建一个新数组,该数组填充了在调用数组中每个元素上调用提供的函数的结果。因此,map中的回调应该返回一个项目,并且在您的代码上,回调不会返回任何内容。

对于您而言,最好按以下方式使用Array.forEach

const d = [{
    "dashId": 3,"dashName": "one","dashData": []
  },{
    "dashId": 4,"dashName": "two","dashData": [{
      "nestedId": 1,"nestedData": "how are you"
    }]
  }
];

const res = [{
  "nestedId": 11,"nestedData": "I am fine"
}];

d.forEach(li => {
  if (li.dashId === 3) {
    li.dashData.push(...res)
  }
});

console.log(d);

,

您只需要在 import { TestBed,waitForAsync,async,getTestBed } from '@angular/core/testing'; import { AngularFireModule } from '@angular/fire'; import { AuthGuard } from './auth.guard'; import { AuthService } from '../shared/services/auth.service'; import { ActivatedRouteSnapshot,Router } from '@angular/router'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { environment } from '../../environments/environment'; describe('AuthGuard',() => { let guard: AuthGuard; let injector: TestBed; let authService: AuthService; const routerMock = {navigate: jasmine.createSpy('chats')}; beforeEach(() => { TestBed.configureTestingModule({ providers: [AuthGuard,{ provide: Router,useValue: routerMock }],imports: [ HttpClientTestingModule,AngularFireModule.initializeApp(environment.firebaseConfig) ] }).compileComponents(); guard = TestBed.inject(AuthGuard); }); injector = getTestBed(); authService = injector.inject(AuthService); guard = injector.inject(AuthGuard); it('should be created',() => { expect(guard).toBeTruthy(); }); it('should redirect an unauthenticated user to the login route',waitForAsync(() => { const promise = new Promise(() => {}); promise.then(() => { expect(authService.SignOut).toBeTruthy(); }); })); it('should allow the authenticated user to access app',waitForAsync(() => { const promise = new Promise(() => {}); promise.then(() => { expect(authService.isLoggedIn).toBe(true); }); })); }); 回调中返回li

map

我不确定您需要什么,但我认为let dd = d.map(li => { if (li.dashId === 3) { li.dashData.push(res) } return li }) 不应该是数组:

res

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...