2

I want to create an object which looks like the below code:

MyObject ={
 "United Kingdom":{
    "primary":{ 

    },
    "secondary":{

    },
    "service":{

    },  
},

"France":{
    "primary":{


    },
    "secondary":{

    },
    "service":{

    },  
},

What I want to do is automatically generate the object from an array, so I have two arrays:

CountryList = ["United Kingdom", "France"]

MarketList = ["primary", "secondary", "service"]

I'm doing it through a for loop

for (var i = 0; i < CountryList.length; i++) {
  for(var p = 0; p < MarketList.length; p++)
      MyObject[CountryList[i]][MarketList[p]] = self;
}

However I'm getting an error:

Cannot set property 'primary' of undefined

Any ideas on where I am wrong? It functions fine when looping through the country list but when I want to nest the "Market" object inside I get a problem.

Thanks!

epayne
  • 149
  • 1
  • 7
  • 1
    You have to create the property, before you can assign another property to that one. – evolutionxbox Mar 15 '17 at 12:36
  • Possible duplicate of [JavaScript - cannot set property of undefined](http://stackoverflow.com/questions/7479520/javascript-cannot-set-property-of-undefined) – Rajesh Mar 15 '17 at 12:39

3 Answers3

1

You need an object before assigning a property to it

myObject[countryList[i]] = {};

Juist a hint, variables with capital letter and following small letters denotes classes or functions which can be used as constructor.

var myObject = {},
    countryList = ["United Kingdom", "France"],
    marketList = ["primary", "secondary", "service"],
    i, p;

for (var i = 0; i < countryList.length; i++) {
    myObject[countryList[i]] = {};
    for (p = 0; p < marketList.length; p++) {
        myObject[countryList[i]][marketList[p]] = {};
    }
}

console.log(myObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You need to add a condition to test if MyObject[] is not undefined.

if (MyObject[CountryList[i]]) {
      MyObject[CountryList[i]][MarketList[p]] = self;      
}

I think, the error you mentionned will be no more.

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
0

With ES6 you can use object destructuring to get two variables, and reduce() to create that object.

var MyObject ={"United Kingdom":{"primary":{},"secondary":{},"service":{}},"France":{"primary":{},"secondary":{},"service":{}}}

var result = Object.keys(MyObject).reduce(function(r, e) {
  if (!r.CountryList || !r.MarketList) r.CountryList = [], r.MarketList = []
  r.MarketList = [...new Set(r.MarketList.concat(Object.keys(MyObject[e])))]
  r.CountryList.push(e)
  return r
}, {})

var {MarketList,CountryList} = result
console.log(MarketList)
console.log(CountryList)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176