【发布时间】: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 中删除 car2 和 car4,使用它的索引位置,如 [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