如何在 JavaScript 中向现有对象添加一组完整的键:值对?



如何在javascript中向现有对象添加一组完整的键:值对?

您可以使用推送方法,而不是使用分配并将元素添加到艺术家数组中,下面的代码片段附上,希望对您的问题有所帮助。

let artists = [];
artists.push({
"id": 1,
"name": "Tommy Gunzz1",
"years": "1971 - 2020",
"genre": "Web Design1",
"nationality": "American Earthling",
"bio": "Tommy Gunzz, formerly known as Tom Harris III, was born in Baltimore MD. Tom Harris was wisked away from his life to retreat to Alabama with His Mother, Mary Ella Vaughn Harris, Life would never be the Same!"
});
function addArtist(dataToAdd) {
artists.push(dataToAdd);

}
var dataToAdd = {
"id": 2,
"name": "Tommy Gunzz2",
"years": "1971 - 2020",
"genre": "Web Design",
"nationality": "American Earthling",
"bio": "Tommy Gunzz, formerly known as Tom Harris III, was born in Baltimore MD. Tom Harris was wisked away from his life to retreat to Alabama with His Mother, Mary Ella Vaughn Harris, Life would never be the Same!"
};

console.log("before adding",artists.length);
addArtist(dataToAdd);
console.log("after adding",artists.length);

使用新数据推送到数组

let artists = [{name: 'Artist1'}]; // Initial array of artist objects
function addArtist(newArtist) {
artists.push(newArtist); // Pushing to the artists array
}
console.log(artists);
addArtist({name: 'Artist2'}); // Calling the addArtist
console.log(artists);

最新更新