I am using Vue project to my mini search system and its database is firebase. I would like to know if these is a language error or its library error. where the Array.push() is not working properly.
I could show only screen shot because it could not show in other reproduction when I reproduce the code.
let trainVal1 = []
for(let n in dataTrainingVal) {
console.log({key: n, ...dataTrainingVal[n]})
trainVal1.push({key: n, ...dataTrainingVal[n]})
console.log(trainVal1)
}
thanks!
Just create a object for the {key: n, ...dataTrainingVal[n]}
like var obj = {key: n, ...dataTrainingVal[n]}
. Then push it.
var trainVal1 = []
for(let n in dataTrainingVal) {
var obj = {key: n, ...dataTrainingVal[n]}
trainVal1.push(obj)
console.log(trainVal1)
}
try also var insted of let
you should change your code like below
let trainVal1 = []
for(let n = 0; n < dataTrainingVal.length; n++) {
console.log({key: n, data:dataTrainingVal[n]})
trainVal1.push({key: n, data:dataTrainingVal[n]})
console.log(trainVal1)
}
The error is on the spread operator section. I have updated your code to a working solution.
let trainVal1 = [] let dataTrainingVal = [1,2,3] for(let n in dataTrainingVal) { console.log(dataTrainingVal[n]) trainVal1.push({key: n, val: dataTrainingVal[n]}) console.log(trainVal1) }
Please note: Do not use for in loop for array iterations.
Note: for...in should not be used to iterate over an Array where the index order is important. Read More on MDN
It seems to work fine... the only missing piece is defining dataTrainingVal.
let trainVal = []
let dataTrainingVal = {firstname: 'Pedro', lastName: 'Juan'}
for(let n in dataTrainingVal) {
console.log({key: n, ...dataTrainingVal[n]})
trainVal.push({key: n, ...dataTrainingVal[n]})
console.log(trainVal)
}
The o/p :
(2) [{…}, {…}]
0: {0: "P", 1: "e", 2: "d", 3: "r", 4: "o", key: "firstname"}
1: {0: "J", 1: "u", 2: "a", 3: "n", key: "lastName"}
length: 2
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.