我正在重构一些旧的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"]
但是我需要为每个新属性创建一个新变量,想知道有人提出一些建议吗?我想过只编写一个函数,它接受属性并从给定数组中提取值
答案 0 :(得分:0)
为什么不直接合并数组服务器并将其加载到您的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];
}
}