Javascript, repeating an object key N-times, being N its value

后端 未结 6 1011
有刺的猬
有刺的猬 2020-12-20 01:11

I was wondering how to do this in the more cleaner and optimal way:

I have an Object with the following structure:

{
   \"125\": 2,
   \"439\": 3,
           


        
6条回答
  •  我在风中等你
    2020-12-20 01:34

    The problem with the other answers above is that the for..in language construct in javascript is going to involve all keys from the objects prototype chain. In this case, we should check and add only the correct keys.

    var obj= {
       "125": 2,
       "439": 3,
       "560": 1,
       "999": 2
    }
    
    var arr=[];
    
    for (var item in map) {
      //important check!
      if (map.hasOwnProperty(item)) {
        arr.push(item);
      }
    }
    

    Also see: http://www.yuiblog.com/blog/2006/09/26/for-in-intrigue/

提交回复
热议问题