简体   繁体   English

从 object 中的数组中删除除特定项之外的所有项目

[英]Remove all items except specific from array inside object

Trying to remove all items from the array inside object but getting this error Cannot delete property '0' of [object Array]试图从 object 中的数组中删除所有项目,但出现此错误无法删除 [object Array] 的属性“0”

object array: object 阵列:

       let tempBrand = [
          {
         name: "Toshiba",
         models:["Toshiba Excite Pro","Toshiba Regza AT300","Toshiba Regza AT1S0","Toshiba Folio 
         100","Toshiba G500","Toshiba AT720"]
         }
        ]

       let tagsData= ["Toshiba Regza AT300","Toshiba Regza AT1S0"]

this is what I'm trying to do.这就是我想要做的。

       for (let i = 0; i < tempBrand.length; i++){
            tempBrand[i].models.length = 0;
            for (let j = 0; j < tempBrand[i].models.length; j++){
                if (tempBrand[i].models[j] !== tagsData[i]) {
                    delete tempBrand[i].models[j];
                }
            }
        }

I am unable to understand exactly what you are trying to achieve but here is my implementation about what I understood from your problem.我无法准确理解您要实现的目标,但这是我从您的问题中理解的实现。 As you have updated the question here is the updated answer.正如您更新的问题,这里是更新的答案。 If you want to persist with the iterative approach you can use that or else as mentioned in the comments you can use es6 methods for functional style of coding.如果您想坚持使用迭代方法,您可以使用该方法,或者如评论中所述,您可以使用 es6 方法进行函数式编码。

let tempBrand = [
         {
         name: "Toshiba",
         models:["Toshiba Excite Pro","Toshiba Regza AT300","Toshiba Regza AT1S0","Toshiba Folio 100","Toshiba G500","Toshiba AT720"]
        }
        ]

       let tagsData= ["Toshiba Regza AT300","Toshiba Regza AT1S0"];
 
 for (let i=0 ; i<tempBrand.length;i++)
for(let j=0 ; j<tempBrand[i].models.length;j++){
    if(tagsData.includes(tempBrand[i].models[j]))
    {
      console.log({item : tempBrand[i].models[j]});
      tempBrand[i].models.splice(j, 1); 
     }   
}
console.log({tempBrand})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM