1

I have an object that looks like this:

var obj = {
    "cat" : [
        {val: 'res', string: "Residential & Single Family Homes"},
        {val: 'Dup', string: "Duplexes & Apartments"},
        {val: 'Con', string: "Condominiums"},
        {val: 'Lot', string: "Lots, Land & Farms"},
        {val: 'Com', string: "Commercial"},
        {val: 'Mob', string: "Mobile Homes"},
    ],
    "bdrms" : [
        {val: "1", string: "1 Bedroom"},
        {val: "2", string: "2 Bedrooms"},
        {val: "3", string: "3 Bedrooms"},
        {val: "4", string: "4 Bedrooms"},
        {val: "5", string: "5 Bedrooms"},
    ],
    "bthrms" : [
        {val: "1", string: "1 Bathroom"},
        {val: "1.1", string: "1 1/2 Bathrooms"},
        {val: "2", string: "2 Bathrooms"},
        {val: "2.1", string: "2 1/2 Bathrooms"},
        {val: "3", string: "3 Bathrooms"},
        {val: "3.1", string: "3 1/2 Bathrooms"},
        {val: "4", string: "4 Bathrooms"},
        {val: "4.1", string: "4 1/2 Bathrooms"},
        {val: "5", string: "5 Bathrooms"},
    ],
    "zip" : [

    ]
};

and what i would like to do is dynamically generate an array of zip codes inside "zip" using a for loop. what I have so far isnt working as I am getting a bunch of errors such as unexpected token ect...

im assuming that i am doing this totally wron, but this is what i am attempting to do:

"zip" : [
    for(i=43000; i<=45999;){
        {val: i, string: i},
        i++
    };
]
1
  • Just as an FYI, you may get some weird behavior with a property named string. I believe that's typically a reserved word in JavaScript... Commented Jul 16, 2015 at 18:02

6 Answers 6

4

The simplest thing is just to do it after the object initializer:

for(i=43000; i<=45999;i++){
    obj.zip.push({val: i, string: i});
}

(Note that I moved the i++, it has no business being in the body of the loop.) (Also note that unless you have i declared somewhere, that was falling prey to The Horror of Implicit Globals.) (And for blocks don't have a ; after them. :-) )

If it were really important that it be part of the initializer (which is unlikely), you could use a temporary function you call immediately:

"zip" : function() {
    var a = [];
    for(var i=43000; i<=45999;i++){
        a.push({val: i, string: i});
    }
    return a;
}()

...but I wouldn't without a good reason. Though I'm not sure why not...

Sign up to request clarification or add additional context in comments.

5 Comments

by "after the object initialize" do you mean outside of var obj = {...}; ?
for closure +1, even though only use is redability! And it's not a bad practice to initialise this way, so long as each initialisation does not contain any logic a model shouldn't have
@War10ck no ] should be needed can you elaborate
@prakharsingh95: He was commenting on an earlier version of the answer that had a typo.
@DestinationDesigns: Yes. Specifically, after it.
2

Just have an empty array zip: [] and then use a loop to push objects containing the values into it, making sure you var your loop variables:

for (var i = 43000; i <= 45999; i++) {
    obj.zip.push({ val: i, string: i });
};

DEMO

Comments

1

"zip" : [ <---- Having a loop inside an array will throw an error for(i=43000; i<=45999;){ {val: i, string: i}, i++ }; ]

Supposed to look like

"zip": function () { //<--- Need to write up a function
    var arr = [];    // that will return an array instead
    for (var i = 43000; i <= 45999; i++) {
        var oo = {   // 
            val: i,
            string: i
        };
        arr.push(oo);
    };

    return arr;

}()

So basically it is a function that computes the array and returns the zip codes.

Comments

0
var zip = [];
for (var i = 43000; i <= 45999; i++) {
    zip.push({val: i, string: i});
}
console.log(zip);

Will output the zip array containing the objects you desire.

Edit: Beaten to the punch by Andy!

Comments

0

Try this as a simple readable solution:

"zip": getZipCodes()

function getZipCodes() {
    var codes = [];
    for(var i = 43000; i <= 45999; i++){
        codes.push({val: i, string: i});
    }

    return codes;
};

That way you do not modify the object after creation.

Comments

-2

You can't run your loop inside of the array literal. This will work:

   var obj = {
        "cat" : [
            {val: 'res', string: "Residential & Single Family Homes"},
            {val: 'Dup', string: "Duplexes & Apartments"},
            {val: 'Con', string: "Condominiums"},
            {val: 'Lot', string: "Lots, Land & Farms"},
            {val: 'Com', string: "Commercial"},
            {val: 'Mob', string: "Mobile Homes"},
        ],
        "bdrms" : [
            {val: "1", string: "1 Bedroom"},
            {val: "2", string: "2 Bedrooms"},
            {val: "3", string: "3 Bedrooms"},
            {val: "4", string: "4 Bedrooms"},
            {val: "5", string: "5 Bedrooms"},
        ],
        "bthrms" : [
            {val: "1", string: "1 Bathroom"},
            {val: "1.1", string: "1 1/2 Bathrooms"},
            {val: "2", string: "2 Bathrooms"},
            {val: "2.1", string: "2 1/2 Bathrooms"},
            {val: "3", string: "3 Bathrooms"},
            {val: "3.1", string: "3 1/2 Bathrooms"},
            {val: "4", string: "4 Bathrooms"},
            {val: "4.1", string: "4 1/2 Bathrooms"},
            {val: "5", string: "5 Bathrooms"},
        ],
        "zip" : [

        ]
    },
    zips = obj.zip,
    i,
    counter = 0,
    j;
    for(i=43000; i<=45999; i++){
        zips[counter] = { val: i, string: i };
        counter++
    };

5 Comments

counter = i always. Js engine will auto optimise this, but it's bad for redability
I agree it would have been better to use push, and I also agree that using "i' for a counter is pretty standard, but I haven't heard the "counter = i always" rule. Do you have a link to any documentation on this that I can read up on?
@prakharsingh95 counter = i is usually true if you're starting with i = 0. In this case, though, that doesn't hold true. counter should be 0 and i should be 43000. It's not a clean solution by any accounts but this would definitely work
@dgavian sorry I meant counter is just an offset from i. You are incrementing both when you only need to increment one. you could do zips[counter-43000]
@War10ck I clarify. If two variables have an unchanging relationship, and mathematically trivial keep only one. For ex, js engine or a compiler will automatically do this, and it's easier to read with one variable.

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.