0

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.

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 ?

2
  • Object should contain key: value pair Commented Apr 11, 2022 at 10:09
  • 1
    forEach always returns undefined. You might be looking for .map() but your convert does not return anything, either. Commented Apr 11, 2022 at 10:11

1 Answer 1

1

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

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

3 Comments

is the flat necessary. map and item[0]?
You are right. Sorry i missed that. Thanks for pointing that out. I updated the answer.
Thanks, thats explain a lot. And its even simpler and straight forward.

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.