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!

2

3 Answers 3

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

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

Comments

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.

Comments

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)

Comments

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.