简体   繁体   English

根据对象属性创建数组

[英]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: 我知道我可以像这样遍历object的属性:

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() : 使用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)); 

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

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