gpt4 book ai didi

javascript - 在插入数组之前检查 Obj Id 值

转载 作者:行者123 更新时间:2023-11-30 19:13:08 25 4
gpt4 key购买 nike

我有两个对象数组。我需要将对象从一个数组插入另一个数组,但在这样做之前我需要检查对象 ID。如果 id 已经在主数组(songDatabase)中,有没有办法增加 obj Id 而不是覆盖或具有重复的 id?

这是我目前的代码:

onst songDatabase = [{ songId: 1, title: 'Drive', artist: 'The Cars', },
{ songId: 2, title: 'When Doves Cry', artist: 'Prince', },
{ songId: 3, title: 'Butterfly', artist: 'Crazy Town', },
{ songId: 4, title: 'The Way I Are', artist: 'Timbaland', },];

const songList = [{ songId: 5, title: 'Save a prayer', artist: 'Duran Duran', },
{ songId: 1, title: 'Sunday Blood Sunday', artist: 'U2', }];

function checkSongId(songIdCheck) {
for (let i = 0; i < songDatabase.length; i++){
songIdCheck = songDatabase[i].songId; //read the songId from songDb
console.log(songIdCheck); //log each songId
}
if(songIdCheck === getNewSong(songList.songId)) { //check if the songId is already on the songDatabase
songIdCheck =+ songIdCheck;
} else {
songDatabase.push(songList);
}
// console.log('song already on the DB');
return;
}

function getNewSong(songId, title, artist) {
for (let x = 0; x < songList.length; x++ ) {
songId = songList[x].songId;
title = songList[x].title;
artist = songList[x].artist;
}
return {songId, title, artist}; //only returns the last songList Object
}

console.log(checkSongId());
console.log(getNewSong());

我希望看到所有歌曲都进入带有唯一 ID 的 songDatabase,但我做不到。任何帮助表示赞赏。

最佳答案

一种更简单的方法可能是将新数组过滤为仅包含旧歌曲数组中不存在的歌曲,然后连接两个数组。如果需要的话,你也可以把它写回 oldSongArray

let oldSongArray; //existing db
let newSongArray; //new db

let updatedSongArray = oldSongArray.concat(newSongArray.filter(_song => !oldSongArray.find(song => song.songId === _song.songId)))

// oldSongArray = updatedSongArray;

关于javascript - 在插入数组之前检查 Obj Id 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58274373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com