问题
I had element of _assignedTripData Array like this.
0: {id: 100959872, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
1: {id: 100952759, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
2: {id: 100952761, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
3: {id: 100952766, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
But when I splice element at 0 Position using _assignedTripData.splice(0,1) and store into var newArray = new Array(); after that i want to insert same record at same position using _assignedTripData.splice(0,0,newArray) the final output will become is
Just See 0 index of array it is object why?
0: [{…}]
1: {id: 100952759, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
2: {id: 100952761, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
3: {id: 100952766, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
At 0 position array Object is added because of that when I bind _assignedTripData data to tboday at first record undefined show.
My question is that how to remove array at 'x' position and add them on same position so that array object structure does not change. Reply any Suggestion. I was new in Jquery.
回答1:
From docs, Array.splice returns
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
Hence, you need to use Spread Syntax to achieve the desired result.
let arr = [1,2];
let v = arr.splice(0,1);
arr.splice(0,0, ...v);
console.log(arr);
回答2:
My initial thoughts if you're just replacing an element in the same position, just overwrite it directly
const m = ['a','b','c']
// replace 2nd element directly
m[1] = 'z'
console.log(m)
If you don't know ahead of time wether you'll insert something, you'll have to keep track of those positions
let m = ['a','b','c']
const insertionPoints = []
// remove 2nd element
idxToRemove = 1
m.splice(idxToRemove, 1)
console.log(m) // proof that 2nd element removed
// track that you removed the 2nd element
insertionPoints.push(idxToRemove)
/* at some point in the future... */
// insert at old pos
locationToInsert = insertionPoints.pop()
thingIWantInserted = 'z'
m.splice(locationToInsert, 0, thingIWantInserted)
console.log(m) // show updated
Cheers,
来源:https://stackoverflow.com/questions/52640538/how-to-add-array-in-array-element