简体   繁体   中英

.findIndex is not a function for the array of object

I define en array in TypeScript:

caseLocations: Array<CaseLocation>()

caseLocations gets following data:

{0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}}

When I try to run

state.results.caseLocations.splice(
    state.results.caseLocations.findIndex((i) => i.objectid === action.objectId), 1
);

I get an error:

caseLocations.findIndex is not a function

Why it is not working? I tried also .map function. The same error.

caseLocations is an object, but with number as keys.

You can know that because the brackets around the data you provided us {} means it's an object.

If it were an array it should have been like this: [0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}] . With those brackets: [] .

caseLocations is an object, not an array. To use array methods such as splice or findIndex you have to convert it to an array first using the Object.values() function:

state.results.caseLocations = Object.values(state.results.caseLocations);

state.results.caseLocations.splice(
    state.results.caseLocations.findIndex((i) => i.objectid === action.objectId), 1
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM