使用另一个数组按索引删除数组中的对象

Deleting objects in an array by index using another array

本文关键字:数组 对象 删除 另一个 索引      更新时间:2023-09-26

我有一个对象数组:

{ key : "value", key2 : "value2", key3 : "value3", key4 : "value4", key5 : "value5" }

我还有一个标准数组:

[1, 3, 5]

我将如何使用第二个数组中的值删除第一个数组中的对象,因此我最终会得到这个:

{ key2 : "value2", key4 : "value4" }

谢谢!

事实证明,

这是一个不平凡的答案,因为键在对象中没有一致的约定。

第一个没有索引(key),其余的有基于1的索引(key2key3key4...),不像常规的Javascript数组。

解决这个问题的最好方法是使用 ES5 Object.keys 方法,并记住我们需要减去 1 来考虑基于 1 的索引。

Object.keys 返回所有键(作为数组从作为第一个参数传递的任何内容。

var obj = { hello: 0, world: 1 };
Object.keys(obj); // ['hello', 'world']

我们可以将此键列表与您提供的用于删除键的索引一起使用。

var deletion = [1, 3, 5];
var object = { key : "value", key2 : "value2", key3 : "value3", key4 : "value4", key5 : "value5" };
var keys = Object.keys(object);
object[keys[1]] // key2
object[keys[3]] // key4
object[keys[5]] // undefined

几乎,但我们还没有更正索引。 1 实际上应该与数组的第一个元素相关,但 Javascript 使用 0 代替。

object[keys[1 - 1]] // key
object[keys[3 - 1]] // key3
object[keys[5 - 1]] // key5

最后,由于Javascript支持反射,我们可以使用这些键来实际修改对象。

当您要从对象中删除它们时,我们需要 delete 运算符。

删除运算符从对象中删除属性。

将它们放在一起,您将获得:

var object = { key : "value", key2 : "value2", key3 : "value3", key4 : "value4", key5 : "value5" };
var deletion = [1, 3, 5];
var keys = Object.keys(object);
deletion.forEach(function(index) {
  delete object[keys[index - 1]];
});

编辑:但是,正如@adeneo评论中指出的那样

Object.keys 中没有任何顺序保证,它可以以它想要的任何顺序返回键,它是"依赖于实现的"。但是,所有浏览器通常会按顺序返回密钥,但这不应该依赖

这意味着您最终可能会完全删除错误的密钥,最终可能成为一个灾难性的错误。

可以通过

稍微不那么可靠的方式规避此行为。

var object = { key : "value", key2 : "value2", key3 : "value3", key4 : "value4", key5 : "value5" };
var deletion = [1, 3, 5];
function indexToKey(index) {
  return 'key' + (index > 1 ? index : '');
}
deletion.forEach(function(index) {
  delete object[indexToKey(index)];
});

此实现不太可靠,因为它固有地将实现与密钥命名结构相关联。

一个简单的方法:

var obj = {
  key:  "value",
  key2: "value2",
  key3: "value3",
  key4: "value4",
  key5: "value5"
};
var indices = [1,3,5];
var result = removeKeys(indices, obj);
alert(JSON.stringify(result, null, 4));
<script>
function removeKeys(indices, obj) {
  var index = createKeyIndex(indices);
  return removeIndex(index, obj);
}
function removeIndex(index, obj) {
  var keys   = Object.keys(obj);
  var length = keys.length;
  var result = {};
  var i      = 0;
  while (i < length) {
    var key = keys[i++];
    if (!index.hasOwnProperty(key))
      result[key] = obj[key];
  }
  return result;
}
function createKeyIndex(indices) {
  var length = indices.length;
  var index  = {};
  var i      = 0;
  while (i < length) {
    var n      = indices[i++];
    var key    = "key" + (n === 1 ? "" : n);
    index[key] = true;
  }
  return index;
}
</script>

createKeyIndex函数返回键数组的索引对象。它允许您测试输入数组在O(1)时间内是否具有给定的键。对于长度n数组O(n)创建索引需要时间。

例如,createKeyIndex([1,3,5])会导致{ key:true, key3:true, key5:true } .

removeKeys 函数创建给定索引数组的索引对象,然后仅添加那些不在给定索引数组中的键。对于长度为m的对象,删除不需要的键需要O(n) + O(m)时间。O(n)时间是创建索引对象的时间。