好的,所以我完成了Record Collection教程,并对最初的挑战有了相当扎实的理解。但是,我希望我的函数能够将新ID添加到集合中(如果尚不存在)。我已经尝试了很多变体,但是我不知道该怎么做(菜鸟-_-)。我知道这是没有必要的,但是我认为这无论如何都会有助于我对对象和数组的整体理解。
以下代码是我的最新尝试。第一个if语句是我的附加组件。我应该首先使用.hasOwnProperty运行if语句吗? Idk。请用假术语解释。 :)
var collection = {
2548: {
album: "Slippery When Wet",
artist: "Bon Jovi",
tracks: [
"Let It Rock",
"You Give Love a Bad Name"
]
},
2468: {
album: "1999",
artist: "Prince",
tracks: [
"1999",
"Little Red Corvette"
]
},
1245: {
artist: "Robert Palmer",
tracks: []
},
5439: {
album: "ABBA Gold"
}
};
function updateRecords(id, prop, value) {
// If the id is not blank and the prop is not blank,
if (id !== "" && prop !== "") {
// then create the new id name and push the property onto it.
collection.id = [];
collection[id].push(prop);
}
//If the property is equal to "tracks" and the tracks value isn't empty,
else if (value !== "" && prop === "tracks") {
//update or set the value for the property.
collection[id][prop].tracks;
//If the specificied id doesn't have the property tracks,
} else if (!collection[id].hasOwnProperty("tracks")) {
//then add the property tracks and push in the track's name value
collection[id].tracks = [];
collection[id].tracks.push(value);
//Otherwise delete the id entirely.
} else {
delete collection[id][prop];
}
return collection;
}
updateRecords(2005, "tracks", "check on it");
答案 0 :(得分:-1)
如果您试图确保在将记录添加到集合之前不存在该记录,那么最简单的方法是使用类似Array.find
的方法。
以下代码仅检查id
字段以查看其是否已存在。在您的方案中,您可能需要检查其他属性,因此您的.find
将进行一些额外的检查。
示例:
const records = [
{ id: 1, name: 'Test1' },
{ id: 2, name: 'Test2' },
{ id: 3, name: 'Test3' },
{ id: 4, name: 'Test4' },
];
const addRecord = (record) => {
if (record) {
const existingRecord = records.find(r => r.id === record.id);
if (existingRecord) { return `Record ${record.id} already exists`; }
records.push(record);
return records;
}
return 'Record cannot be falsy';
}
console.log(addRecord({ id: 5, name: 'Test5' })); // Adds record
console.log(addRecord({ id: 1, name: 'Test123123123 doesnt matter' })); // Record already exists
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
示例为object
集合而不是array
的{{1}}
objects
答案 1 :(得分:-2)
另一种方法:
let records = {
1: { name: 'Test1' },
2: { name: 'Test2' },
3: { name: 'Test3' },
4: { name: 'Test4' }
}
const addRecord = (id, name) => {
if (!id || !name) {
return 'Id and name must be defined'
}
const exists = Object.keys(records).some(recordId => +recordId === id)
if (exists) {
return `${id} already exists`
}
records[id] = { name }
return records
}
console.log(addRecord(5, 'Test5')) // Adds record
console.log(addRecord(1, 'blag asdfsdafafds')) // Already exists