简体   繁体   English

删除对象属性是否像使用拼接删除数组元素一样?

[英]Delete object properties similiar like deleting array elements with splice?

We have object type variable in Jquery: 我们在Jquery中有对象类型变量:

var obj = *{"1234" : "xx", "4321" : "yy", "5555" : "hh", "2321" : "aa" };*

Lets say that I want to delete every property from property name "5555" to the end of the object(that means that I want to delete obj['5555'] and delete obj['2321'] ). 可以说,我想从属性名称“ 5555”到对象末尾删除每个属性(这意味着我要delete obj['5555']delete obj['2321'] )。 I am interested in smartest way, trough loop, to do that. 我对最聪明的方式-槽循环-感兴趣。

In array I would use splice(2, arr.length) but I am confused. 在数组中,我将使用splice(2, arr.length)但我感到困惑。

There's no guarantee as to the order of an object's properties. 无法保证对象属性的顺序。 When pasting your example object in my console, Here's what I saw: 在控制台中粘贴示例对象时,这是我看到的内容:

> obj = {"1234" : "xx", "4321" : "yy", "5555" : "hh", "2321" : "aa" }
  Object {1234: "xx", 2321: "aa", 4321: "yy", 5555: "hh"}

As you can see, chrome ordered the properties in ascending order, like it would an array. 如您所见,chrome像数组一样按升序对属性进行排序。 Who knows, but maybe IE doesn't do this... Maybe some obscure browser would order the properties in descending order... There's no way of knowing what the actual object will look like, so perhaps have a rethink. 谁知道,但也许IE不会这样做...也许某些晦涩的浏览器会按降序对属性进行排序...无法知道实际对象的外观,因此可能需要重新考虑。
If all your properties are, essentially numeric, there's nothing wrong with using an array, in JS, the Array prototype is nothing but an augmented Object : 如果您的所有属性本质上都是数字,那么使用数组没有什么问题,在JS中, Array原型不过是增强Object

obj = [];
obj[1234] = 'xx';
obj[2321] = 'aa';
obj[5555] = 'hh';

The numeric indexes are coerced to strings internally anyway (because Array's are objects), so JS isn't going to create endless empty indexes for you, it resolves obj[200] just like it would resolve objectLiteral.undefinedProperty : scan instance, then prototypechain. 无论如何,数字索引在内部都被强制转换为字符串(因为Array是对象),因此JS不会为您创建无尽的空索引,它解析obj[200]就像解析objectLiteral.undefinedProperty :扫描实例,然后原型objectLiteral.undefinedProperty If the requested property wasn't found, return undefined. 如果找不到请求的属性,则返回undefined。

They're added as you go along, yet here are 2 ways: 它们会随着您的添加而添加,但是有两种方法:

//Assume simpel object (non-nested)
var newObj = JSON.parse(JSON.stringify(obj).replace(/\{|,\s*"5{4}"\s*:.+$/,'}'));

This, I think, is the easiest way, but not very reliable. 我认为这是最简单的方法,但不是可靠。 The most "tried and tested" apprach is: “久经考验”的方法是:

var unset = false;
for (var prop in obj)
{
    if (obj.hasOwnProperty(prop))
    {
        unset = unset || !!(prop === '5555');
        if (unset === true)
        {
            delete(obj[prop]);
        }
    }
}

The last approach creates an array, containing all keys, which you can iterate over, and delete the properties that way. 最后一种方法是创建一个包含所有键的数组,您可以对其进行迭代,然后以这种方式删除属性。 It's here for completeness' sake only: I wouldn't use it, though, simply because it requires a browsers that supports the ES5 spec (not all browsers do, sadly), and there's no real advantage over the code above: 它只是出于完整性的考虑:但是,我不会使用它,只是因为它需要支持ES5规范的浏览器(不幸的是,并非所有浏览器都支持),并且上面的代码没有真正的优势:

var keys = Object.keys(obj).sort(),//call sort to assure ascending order
toDelete = keys.splice(keys.indexOf('5555'), keys.length).sort();
for(var i=0;i<toDelete.length;i++)
{
    delete obj[toDelete[i]];
}

I would recommend you to get the index of the element from which you want to start deleting elements and then looping throw the object deleting the elements with a higher index. 我建议您获取要从其开始删除元素的元素的索引,然后循环抛出该对象,以删除具有较高索引的元素。

You might want to create a function to make it more similar to splice i you prefer. 您可能想要创建一个函数,使其与您喜欢的splice更加相似。

找到您要查找的元素,并将该特定元素及其后的任何元素设置为null

Push the obj to be searched and the value to be found into a function that returns a new object with only those properties up to the value you specified. 将要搜索的obj和要查找的值推送到一个函数中,该函数将返回仅包含那些不超过您指定值的属性的新对象。

function returnNewobj(obj, value) {
  var newObj = {};
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      if (prop === value) return newObj;
      newObj[prop] = obj[prop];
    }
  }
  return newObj;
}

Edit: probably not necessary, but I added the hasOwnProperty line to be on the safe side. 编辑:可能没有必要,但是我添加了hasOwnProperty行是安全的。

Edit2: It's worth pointing out that new properties are added to objects in alphanumerical order, not to the end of objects like elements are added to arrays. Edit2:值得指出的是,新属性是按字母数字顺序添加到对象的,而不是像元素添加到数组那样添加到对象的末尾。 So don't get caught out by that. 因此,不要被那吸引住。

Its very tricky to delete property name however property value can be made null or undefined but removing property is difficult but you can do one thing can copy the required properties in new object its a workaround though here is a sample fiddle i use this often in this kind of situation 删除属性名称非常棘手,但是可以将属性值设置为null或未定义,但是很难删除属性,但是您可以做一件事,即可以将所需属性复制到新对象中,这是一种解决方法,尽管这是一个示例小提琴,我经常在此使用那种情况

    objCopyTo[strToPropertyName] = objCopyFrom[strPropertyName];

here is the fiddle 是小提琴

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

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