简体   繁体   English

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

[英]Deleting objects in an array by index using another array

I have an array of objects: 我有一个对象数组:

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

I also have an standard array: 我也有一个标准数组:

[1, 3, 5]

How would I delete the objects in the first array, using the values in the second array so I would end up with this: 我将如何使用第二个数组中的值删除第一个数组中的对象,因此我将得出以下结论:

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

Thanks! 谢谢!

This proves to be a non-trivial answer, as the keys don't have a consistent convention within your object. 事实证明,这是一个不平凡的答案,因为键在您的对象中没有一致的约定。

The first one has no index ( key ) and the rest have 1-based indexes ( key2 , key3 , key4 ...) , unlike regular Javascript arrays. 与常规的Javascript数组不同,第一个没有索引( key ),其余有从1开始的索引( key2key3key4 ...)。

The best way to get around that, is to use the ES5 Object.keys method and remember that we need to subtract 1 to account for the 1-based indexing. 解决此问题的最佳方法是使用ES5 Object.keys方法,并记住我们需要减去1来说明基于1的索引。

Object.keys returns all the keys ( as an array from whatever was passed as the first argument. Object.keys返回所有键(作为作为第一个参数传递的值的数组)。

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

We can use this list of keys with the indexes you provide for deleting keys. 我们可以将此键列表与您提供的用于删除键的索引一起使用。

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

Nearly, but we haven't corrected the indexes. 差不多了,但是我们还没有更正索引。 1 should in fact relate to the first element of the array, but Javascript uses 0 instead. 1实际上应该与数组的第一个元素有关,但是Javascript使用0代替。

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

Finally, as Javascript supports reflection we can use these keys to actually modify the object on the fly. 最后,由于Javascript 支持反射,因此我们可以使用这些键实时地修改对象。

Seeing as you want to remove them from the object, we'll need the delete operator. 就像您要从对象中删除它们一样,我们需要delete运算符。

The delete operator removes a property from an object. 删除运算符从对象中删除属性。

Put it all together and you get: 放在一起,您将获得:

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

EDIT: However, as @adeneo pointed out in the comments 编辑:但是,正如@adeneo在评论中指出的那样

there's no guarantee of any order in Object.keys it could return the keys in any order it wants to, it's "implementation dependent". Object.keys中没有任何顺序的保证,它可以按其想要的任何顺序返回键,这是“实现相关的”。 However, all browsers will generally return the keys in order, but that shouldn't be relied on 但是,所有浏览器通常都会按顺序返回键,但这不应该依赖

This means you may end up deleting completely the wrong keys which could end up being a disastrous bug. 这意味着您可能最终会完全删除错误的密钥 ,这最终可能是灾难性的错误。

It's possible to circumvent this behaviour in a slightly less robust way. 可以用不太健壮的方式来规避此行为。

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

This implementation is less robust because it inherently ties the implementation to your key naming structure. 此实现的健壮性较低,因为它固有地将实现与您的键命名结构联系在一起。

A simple way: 一种简单的方法:

 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> 

The createKeyIndex function returns an index object of an array of keys. createKeyIndex函数返回键数组的索引对象。 It allows you to test whether the input array has a given key in O(1) time. 它允许您测试输入数组在O(1)时间内是否具有给定键。 For an array of length n it takes O(n) time to create the index. 对于长度为n的数组,创建索引需要O(n)时间。

For example, createKeyIndex([1,3,5]) results in { key:true, key3:true, key5:true } . 例如, createKeyIndex([1,3,5])结果为{ key:true, key3:true, key5:true }

The removeKeys function creates an index object of the given indices array and then adds only those keys which are not in the given indices array. removeKeys函数创建给定索引数组的索引对象,然后仅添加不在给定索引数组中的那些键。 For an object of length m it takes O(n) + O(m) time to remove the non-required keys. 对于长度为m的对象,需要O(n) + O(m)时间来删除不需要的键。 The O(n) time is for creating the index object. O(n)时间用于创建索引对象。

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

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