How do I delete the created object "bird" from an array by name ie by the keyword "bird"?
var storage = [
{cat: {name: "Garfild", count: 3443, price: 1000}}
];
function addProduct(newProduct) {
storage.push(newProduct);
}
addProduct({dog: {name: "Rex", count: 1488, price: 2000}});
addProduct({bird: {name: "Eagle", count: 4042, price: 3000}});
function deleteProductByName(productName) {
storage.remove(productName);
}
deleteProductByName("bird");
You could iterate from the end of the array and splice the found item, which uses a check if the property exists in the object.
function addProduct(newProduct) {
storage.push(newProduct);
}
function deleteProductByName(productName) {
var i = storage.length;
while (i--) {
if (productName in storage[i]) {
storage.splice(i, 1);
}
}
}
var storage = [{ cat: { name: "Garfild", count: 3443, price: 1000 } }];
addProduct({ dog: { name: "Rex", count: 1488, price: 2000 } });
addProduct({ bird: { name: "Eagle", count: 4042, price: 3000 } });
deleteProductByName("bird");
console.log(storage);
.as-console-wrapper { max-height: 100% !important; top: 0; }
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加