【问题标题】:How to remove a object within an object using the Index and not property name如何使用索引而不是属性名称删除对象中的对象
【发布时间】:2021-03-16 11:31:08
【问题描述】:

原始代码

    let base = {
        brand: 'Ford',
        model: '556',
        licensePlate: 55554,
    };
    
    let carsObj = {};
    let carsArr = [];
    
    for (let i = 1; i < 6; i++) {
        carsObj[`car${i}`] = {
            brand: base.brand,
            model: base.model,
            licensePlate: base.licensePlate + i
        }
        carsArr.push({
            brand: base.brand,
            model: base.model,
            licensePlate: base.licensePlate + i
        });;
    };

日志

    {
      car1: { brand: 'Ford', model: '556', licensePlate: 55555 },
      car2: { brand: 'Ford', model: '556', licensePlate: 55556 },
      car3: { brand: 'Ford', model: '556', licensePlate: 55557 },
      car4: { brand: 'Ford', model: '556', licensePlate: 55558 },
      car5: { brand: 'Ford', model: '556', licensePlate: 55559 }
    }

现在我如何从 carsObj 中删除 car2car4,使用它的索引位置,如 [0] 和 [3],而不是 delete carsObj.car2然后将其存储在 newCarsObj 中,以便记录以下内容:

    {
      car1: { brand: 'Ford', model: '556', licensePlate: 55555 },
  
      car3: { brand: 'Ford', model: '556', licensePlate: 55557 },
    
      car5: { brand: 'Ford', model: '556', licensePlate: 55559 }
    }

not this answer in link - 因为这只是一个具有属性+值的对象。而不是对象中的对象 正在寻找 JavaScript 中的解决方案(没有 jQuery、lodash 等)-在此先感谢。

【问题讨论】:

  • 你不能那样做;属性没有“索引”,它们只有自己的名字。
  • 您可以使用Object.keys() 来获取属性名称数组,但是假设该数组中的特定索引肯定对应于特定属性是一个非常脆弱的想法。

标签: javascript arrays object indexof


【解决方案1】:

这就是你需要的。

 let obj = {
  car1: { brand: 'Ford', model: '556', licensePlate: 55555 },
  car2: { brand: 'Ford', model: '556', licensePlate: 55556 },
  car3: { brand: 'Ford', model: '556', licensePlate: 55557 },
  car4: { brand: 'Ford', model: '556', licensePlate: 55558 },
  car5: { brand: 'Ford', model: '556', licensePlate: 55559 }
}

let removeItems = (arr) => {
  arr.map(x => {
    return Object.keys(obj)[x]
  }).forEach(x => delete obj[x])
}

removeItems([1, 2])

console.log(obj)

【讨论】:

  • 不能保证物业订单,所以这充其量是命中或错过。见:Does JavaScript guarantee object property order?
  • 如果您首先查看创建 obj 的代码,您可以看到属性是有序的。因此,除非为同一个对象调用两次,否则我的解决方案将起作用。
  • '...除非为同一个对象调用两次。' 声明一个函数,该函数只能在单个对象上调用一次,并且只有在已知该物体极其脆弱。
  • 这不是我关心的问题。我相信他/她很快就会意识到这个问题并尝试找到更好的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2021-01-16
相关资源
最近更新 更多