如何在Javascript中切片对象?

时间:2016-09-05 19:23:42

标签: javascript arrays object arguments slice

我试图使用Array.prototype对对象进行切片,但是它返回一个空数组,除了传递参数之外是否有任何切片对象的方法,或者只是我的代码有错误? THX !!

var my_object = {
 0: 'zero',
 1: 'one',
 2: 'two',
 3: 'three',
 4: 'four'
};

var sliced = Array.prototype.slice.call(my_object, 4);
console.log(sliced);

11 个答案:

答案 0 :(得分:27)

尚未提及Object.entries(),这可能是最灵活的方式。枚举属性时,此方法使用与var src = (from row in dt.AsEnumerable() from n in new[]{ row.Field<String>("Name"),row.Field<String>("Surname"),row.Field<String>("SecondSurname")} select n).Distinct().ToArray(); 相同的顺序,即属性最初在对象中输入的顺序。您还可以获得具有属性和值的子数组,以便您可以使用任何一个或两个。最后,您不必担心属性是数字或设置额外的长度属性(就像使用for..in时那样)。
这是一个例子:

Array.prototype.slice.call()

您想要对前两个值进行切片:

const obj = {'prop1': 'foo', 'prop2': 'bar', 'prop3': 'baz', 'prop4': {'prop': 'buzz'}};

所有的钥匙?

Object.entries(obj).slice(0,2).map(entry => entry[1]);
//["foo", "bar"]

最后一个键值对?

Object.entries(obj).slice(0).map(entry => entry[0]);
//["prop1", "prop2", "prop3", "prop4"]

答案 1 :(得分:8)

  

我试图使用Array.prototype切片对象,但它返回一个空数组

那是因为它没有.length属性。它将尝试访问它,获取undefined,将其转换为数字,获取0,并最多切片对象中的许多属性。因此,要实现所需的结果,必须手动通过对象为其分配length或迭代器:

var my_object = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four'};

my_object.length = 5;
console.log(Array.prototype.slice.call(my_object, 4));

var sliced = [];
for (var i=0; i<4; i++)
    sliced[i] = my_object[i];
console.log(sliced);

答案 2 :(得分:3)

var obj = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four'};
var result = Object.keys(obj).slice(0,2).map(key => ({[key]:obj[key]}));

console.log(result);
  

[{'0':'zero'},{'1':'one'}]

答案 3 :(得分:3)

您可以 angular.element($window).bind('resize', function(){ if($window.innerWidth <= 768){ $scope.width =false; }else{ //to disable click of open modal $scope.width =true; //then close your modal forcefully $uibModalInstance.close(); //Run digest $scope.$digest(); }); 函数reduce的结果

Object.keys

答案 4 :(得分:2)

最好的现代解决方案是 Object.fromEntries Object.entries 的组合。

const foo = {
    one: 'ONE',
    two: 'TWO',
    three: 'THRE',
    four: 'FOUR',
}

const sliced = Object.fromEntries(
    Object.entries(foo).slice(1, 3)
)

console.log(sliced)

答案 5 :(得分:1)

我认为它可以帮助你:

var my_object = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four' };

var sliced = Object.keys(my_object).map(function(key) { return my_object[key] }).slice(4);

console.log(sliced);

答案 6 :(得分:1)

尝试将“length”属性添加到my_object,然后您的代码应该有效:

    var my_object = {
     0: 'zero',
     1: 'one',
     2: 'two',
     3: 'three',
     4: 'four',
     length: 5
    };
    
    var sliced = Array.prototype.slice.call(my_object, 4);
    console.log(sliced);

答案 7 :(得分:1)

const res = Object.fromEntries(Object.entries(my_object).slice(0,4));

答案 8 :(得分:0)

除非 [Symbol.iterator]生成器函数和 length属性存在,否则不能这样做。如;

&#13;
&#13;
var my_object = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', length:5 },
       sliced;

my_object[Symbol.iterator] = function* (){
                                          var oks = Object.keys(this);
                                          for (var key of oks) yield this[key];
                                         };

sliced = Array.prototype.slice.call(my_object, 2);
console.log(sliced);
&#13;
&#13;
&#13;

答案 9 :(得分:0)

你没有在你的问题中提到它,但这看起来非常像一个参数对象。

使用Array.from()将其转换为数组,然后像使用任何其他数组一样使用它。只要它是一个可枚举的对象。

对于旧版浏览器的polyfill,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

答案 10 :(得分:0)

&#13;
&#13;
// Works, but acts weird when things get serious
// Avoids screwing with the properties of my_object
// You don't get Object.create() until ES5.1
function lazySlice(obj, idx) {
  var newObj = Object.create(obj, { length: {value: Object.keys(obj).length} }),
  idx = idx || 0;

  return Array.prototype.slice.call(newObj, idx);
}

// Only gives you own enumerable properties with keys "0" to n
// Preserves element order (based on key number)
// Ignores non-numbered keys
// You don't get Object.keys() until ES5
function enumSlice(obj, idx) {
  var arr = [], 
    keys = Object.keys(obj),
    idx = idx || 0;

  for (var i = 0; i <= keys.length - 1; i++)
    if (keys[i] >= idx && keys[i] % 1 === 0 && keys[i] >= 0 && keys[i].indexOf('e') < 0) 
      arr.push(obj[keys[i]]);

  return arr;
}

var my_object = {
  0: 'zero',
  1: 'one',
  2: 'two',
  3: 'three',
  4: 'four'
}; 
console.log(lazySlice(my_object, 3));      // [ 'three', 'four' ]
console.log(enumSlice(my_object, 3));      // [ 'three', 'four' ]

var mixed_object = {
   "9": 'nine',
   "2": 'two',
   "1": 'one',
   "7": 'seven',
   "7.5": 'seven point five',
   "1e4": 'sneaky',
   "-4": 'negative four',
   "0": 'zero',
   "length": 35
};
console.log(lazySlice(mixed_object));      // [ 'zero', 'one', 'two', , , , , 'seven',  ]
console.log(enumSlice(mixed_object));      // [ 'zero', 'one', 'two', 'seven', 'nine' ]
&#13;
&#13;
&#13;