Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting arrays nested in array into object using forEch (does not work somehow?)

I am having trouble with something i thought it will be simple.

I have an array of nested arrays with strings.

const cities = [['Vienna'],['Berlin'],['London'],['Oslo'],['New York']]

I must convert these nested arrays into objects. I think forEach method should suit perfectly along with Object.assign.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I written something like these:

function convert(element) {
    Object.assign({}, element)
  }
  const Test = cities.forEach(convert)

But then i am getting from console.log(Test) undefinded. Why so ? I am iterating through the whole array and each of her arrays should be assign as object. Whats missing ?

>Solution :

Object should contain key: value pair

If you want to convert each string element into an object element. Then you can do something like this :

const cities = [['Vienna'],['Berlin'],['London'],['Oslo'],['New York']]

const res = cities.map((item) => {
    return {
    city: item[0]
  }
});

console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading