繁体   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