-1

I am trying to create an object using the values of items inside an array.

const arrOfObj = [
{city: 'Tokyo', country: 'Japan', ...other values},
{city: 'Paris', country: 'France', ...other values}, 
{city: 'London', country: 'UK', ...other values}, 
{city: 'New York', country: 'USA', ...other values}
]

expected object:

const obj = {
Japan: 'Tokyo', 
France: 'Paris', 
UK: 'London', 
USA: 'New York'
}

Can you guys have any suggestion to achieve this in an efficient way? All the comments will be highly appreciated. Thank you.

2
  • 3
    "I am trying to create an object" - care to show us how? Commented Sep 8, 2019 at 19:17
  • 3
    Possible duplicate of Reduce array to object using arrow function Commented Sep 8, 2019 at 19:17

3 Answers 3

2

Object.fromEntries can be used :

const arrOfObj = [
  { city: 'Tokyo'   , country: 'Japan'  },
  { city: 'Paris'   , country: 'France' }, 
  { city: 'London'  , country: 'UK'     }, 
  { city: 'New York', country: 'USA'    }
]

const obj = Object.fromEntries( arrOfObj.map(o => [o.country, o.city]) )

console.log( obj )

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

Comments

2

You can loop through the array and use the 'country' value as the property and set the value to the value of 'city'.

   const arrOfObj = [
    {city: 'Tokyo', countryL: 'Japan'},
    {city: 'Paris', countryL: 'France'}, 
    {city: 'London', countryL: 'UK'}, 
    {city: 'New York', countryL: 'USA'}
    ]

    let obj = {};
    arrOfObj.forEach(o => {obj[o.countryL] = o.city});

    console.log(JSON.stringify(obj))

Comments

-2

Use Array.prototype.reduce:

arrOfObj.reduce((acc, { city, country }) => {
  acc[country] = city
  return acc
}, {})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

1 Comment

Try to explain your solution when you post an answer

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.