如何通过名称正确删除数组中的对象?

时间:2018-04-29 13:41:53

标签: javascript

如何删除创建的对象" 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");




4 个答案:

答案 0 :(得分:4)

您可以这样做:

storage = storage.filter(item => Object.keys(item)[0] !== 'bird');

答案 1 :(得分:1)

您可以从数组的末尾进行迭代并拼接找到的项目,该项目使用检查对象中是否存在该属性。

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; }

答案 2 :(得分:1)

如果过滤不是你想要的,但你真的将数据删除到原始数组,你可以像这样编写删除:

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) {
    var index=storage.map(function(e) { return Object.keys(e).join(); }).indexOf(productName);
   storage.splice(index,1)
}
deleteProductByName("bird");

console.log(storage)

它完成了这项工作。但我建议进行一些重构。如果希望每个函数都是完全可测试的,则应该将参数注入并避免使用全局变量,从而依赖于使用它的代码。使您的功能不再涉及某些细节。所以你可以有类似的东西:

var storage = [
    {cat: {name: "Garfild", count: 3443, price: 1000}}
];

function addProduct(newProduct) {
     return function(storageArr) {
             storageArr.push(newProduct);
             return storageArr;
       }
}

storage=addProduct({dog: {name: "Rex", count: 1488, price: 2000}})(storage);
storage=addProduct({bird: {name: "Eagle", count: 4042, price: 3000}})(storage);
console.log(storage);

function deleteProductByName(productName) {
    return function(storageArr) {
            var index=storageArr.map(function(e) { return Object.keys(e).join(); }).indexOf(productName);
            storageArr.splice(index,1);
            return storageArr;
        } 
}

storage=deleteProductByName("bird")(storage);
console.log(storage);

答案 3 :(得分:0)

修改您的删除功能,并根据删除是否成功返回false或true:

function deleteProductByName(productName) {
    var index = storage.indexOf(storage.filter(function(d,i){return Object.keys(d)[0] === productName})[0]);
       return !~index ? false : (storage.splice(index,1),true);
  }