简体   繁体   中英

Create array based on object properties

I'd like to use an object to configure some settings for an app. My idea is to start with this:

var obj = {
    property_one: 3;
    property_two: 2;
    property_three: 1;
}

And I would like to end up with this:

var array = [
    'property_one','property_one','property_one',
    'property_two','property_two',
    'property_three'
]

My current solution is to do this for each property:

function theConstructor(){
    for(i=1; i <= obj.property_one; i++){
        this.array.push('property_one');
    };
    for(i=1; i <= obj.property_two; i++){
        this.array.push('property_two');
    };
    for(i=1; i <= obj.property_two; i++){
        this.array.push('property_two');
    };
}

But this gets tedious, because I might have many properties, and these might change as the app evolves.

I know I can loop through object 's properties like this:

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    array.push(key);
  }
}

But this will push the value to the array, not the key (as a string). Any ideas about how I can do this more efficiently?

Try this

function theConstructor(){
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      for(var i=1; i <= obj[key]; i++){
        this.array.push(key);
      };
    }
  }
}

Using Array.prototype.reduce() :

 var obj = { property_one: 3, property_two: 2, property_three: 1 }; var resultArray = Object.keys(obj).reduce(function(result, curItem) { for (var index = 0; index < obj[curItem]; index++) { result.push(curItem); } return result; }, []); document.write(JSON.stringify(resultArray)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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