簡體   English   中英

將重復的PHP屬性重構為JS

[英]Refactoring repetitive PHP properties to JS

我在重構一些舊的PHP代碼,並且有一些類似的重復代碼行,它們使用相同的屬性:

$new_artist["spotify"]["current"]["total_streams"] = $track["spotify"]["current"]["total_streams"];
$new_artist["spotify"]["current"]["total_listeners"] = $track["spotify"]["current"]["total_listeners"];
$new_artist["spotify"]["current"]["source_of_stream"] = $track["spotify"]["current"]["source_of_stream"];
$new_artist["spotify"]["current"]["access_type"] = $track["spotify"]["current"]["access_type"];
$new_artist["spotify"]["current"]["metrics"]["new_collection_listeners"] = $track["spotify"]["current"]["metrics"]["new_collection_listeners"];
$new_artist["spotify"]["current"]["metrics"]["spotify_playlist_placement"] = $track["spotify"]["current"]["metrics"]["spotify_playlist_placement"];
$new_artist["spotify"]["current"]["date"] = $track["spotify"]["current"]["date"]; 

要么

$new_artist["spotify_metadata"]["artist_followers"] = $track["spotify_metadata"]["artist_followers"];
$new_artist["spotify_metadata"]["artist_genres"] = $track["spotify_metadata"]["artist_genres"];
$new_artist["spotify_metadata"]["artist_popularity"] = $track["spotify_metadata"]["artist_popularity"];
$new_artist["spotify_metadata"]["artist_images"] = $track["spotify_metadata"]["artist_images"];

我可以像這樣重構

const newArtist = new_artist["spotify"]["current"];
const spotifyCurrentData = track["spotify"]["current"];
newArtist["total_streams"] = spotifyCurrentData["total_streams"]

但我需要為每個新屬性創建一個新變量,想知道有人提出一些建議嗎? 我考慮過只編寫一個接受屬性並從給定數組中提取值的函數

為什么不只是在服務器端合並數組並將其加載到您的javascript中呢?

$new_artist["spotify_metadata"] = array_merge(
    //Any original content
    $new_artist["spotify_metadata"],
    //Any new content from $track
    $track["spotify_metadata"]
)

在JavaScript中,您必須遍歷鍵並分配它們:

var newArtist = new_artist["spotify"]["current"];
var spotifyCurrentData = track["spotify"]["current"];

for (const key in spotifyCurrentData) {
    if (spotifyCurrentData.hasOwnProperty(key)) {
        newArtist[key] = spotifyCurrentData[key];
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM