简体   繁体   中英

Refactoring repetitive PHP properties to JS

I was refactoring some old PHP code and there were some repetitive lines of code like this, which use the same properties:

$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"]; 

or

$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"];

and I can refactor like:

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

but I would need to create a new variable for every new property, was wondering does anyone some recommendations? I thought about just writing a function which takes in properties and extracts a value from a given array

Why not just merge the arrays serverside and load that into your javascript?

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

In JavaScript you would have to loop over the keys and assign them:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM