[英]Push object into an array
我有需要像下面這樣形成對象的要求
[
{
"place": "Royal Palace, Oslo",
"latitude" : "59.916911"
},
{
"place": "Royal Palace, Oslo",
"latitude" : "59.916911"
}
]
以上位置和緯度值可在地圖功能中用作
let sampleArray = [];
jsonresponse.map((item) => {
let place = item.place;
let latitude = {/*with other logic function we will get latitude value*/}
//need to send these both values into below array to form array shown as above.
sampleArray.push();
})
提前致謝。
您使用的地圖功能錯誤。 在映射函數中,您將創建一個新數組,其中對於每個值,返回值都將替換當前值。 您的函數不會返回新值,也不會將任何內容推入數組。 因此,您有2個選擇:
//FIRST OPTION
const sampleArray = jsonResponse.map(({ place } => ({
place,
latitude: [SOME_VALUE]
}))
//SECOND OPTION
const sampleArray = [];
jsonresponse.forEach(({ place }) => {
sampleArray.push({
place,
latitude: [SOME_VALUE]
})
})
另外,請注意es6的解構語法,它可以為您節省一些代碼。
您需要對Array.prototype.map做的所有事情是:
let sampleArray = jsonresponse.map((item) => {
let place = item.place;
let latitude = {/*with other logic function we will get latitude value*/}
return {
place,
latitude
}
})
這是您要完成的嗎?
let sampleArray = []
jsonresponse.map(item => {
sampleArray.push({
place: item.place,
latitude: {/*with other logic function we will get latitude value*/}
})
})
console.log(sampleArray)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.