0

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?

2 Answers 2

2

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);
      };
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You missed to declare variable i.
Thanks a lot, don't know how I didn't see this looking back!
1

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

1 Comment

Thanks, this is a very elegant solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.