
[英]How can I join an object with arrays into a single array using javascript?
[英]How can I iterate an array of arrays and keep only values from a single index in javascript? [duplicate]
我正在使用easepicker 構建預訂日歷,並使用mySQL 數據庫中的第三方API 導入數據。 我得到了數據庫中的數據,我可以用 Javascript 訪問它(我是新手)。 我正在嘗試從數組數組中刪除除一個以外的所有索引,但無論我如何嘗試執行循環,我都會得到一個未定義的 .pop(),盡管我確保該對象是一個數組數組。
$.ajax({
url : 'get_data.php', // this fetches the booking info from 3rd party => DB
type : 'GET', // type of the HTTP request
success : checkAvail,
});
function checkAvail(response) {
results = response;
var results = jQuery.parseJSON(response);
availables = results.filter(a => a.isAvailable === '1');
console.log(availables); // displays the array of arrays for avail dates
availables.forEach((available) => {
available.pop(2); // **Uncaught TypeError: available.pop is not a function
});
console.table(availables);
}
console.log(availables) 輸出
[
{
"id": "79653836",
"date": "2022-07-09",
"isAvailable": "1",
"price": "2188"
},
{
"id": "79653838",
"date": "2022-07-10",
"isAvailable": "1",
"price": "1750"
},
{
"id": "79653840",
"date": "2022-07-11",
"isAvailable": "1",
"price": "1750"
},
{
"id": "79653842",
"date": "2022-07-12",
"isAvailable": "1",
"price": "1750"
}
]
availables
是一個對象數組,而不是數組數組。
要從對象中獲取特定屬性,請使用.propname
,因此請使用available.date
來獲取日期。
您可以使用map()
返回一個新數組,該數組使用它來獲取屬性。
const availables = [ { "id": "79653836", "date": "2022-07-09", "isAvailable": "1", "price": "2188" }, { "id": "79653838", "date": "2022-07-10", "isAvailable": "1", "price": "1750" }, { "id": "79653840", "date": "2022-07-11", "isAvailable": "1", "price": "1750" }, { "id": "79653842", "date": "2022-07-12", "isAvailable": "1", "price": "1750" } ]; const dates = availables.map(a => a.date); console.log(dates);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.