基于对象属性创建数组

Create array based on object properties

本文关键字:属性 创建 数组 对象 于对象      更新时间:2023-09-26

我想使用一个对象来配置应用程序的一些设置。我的想法是从这个开始:

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

我想以这个结束:

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

我目前的解决方案是为每个属性执行此操作:

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');
    };
}

但这很乏味,因为我可能有很多属性,这些属性可能会随着应用程序的发展而改变。

我知道我可以像这样遍历object的属性:

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

但这会将值推送到数组,而不是键(作为字符串)。关于如何更有效地做到这一点的任何想法?

试试这个

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));