Home > Enterprise >  How to create a named object from an array?
How to create a named object from an array?

Time:10-16

const field = ['name', 'address']

const data = field.map(item => {
  return {item: {mode: 'insensitive', sort: 'desc'}}
})

the variable data above is

[
 {
  item: {
   mode: 'insensitive', 
   sort: 'desc'
  },
  item: {
   mode: 'insensitive', 
   sort: 'desc'
  }
 }
]

I want the value to be

[
 {
  name: {
   mode: 'insensitive', 
   sort: 'desc'
  },
  address: {
   mode: 'insensitive', 
   sort: 'desc'
  }
 }
]

is that possible? or any method to do it better, thank's for your help

CodePudding user response:

You can achieve this by wrapping your item object around brackets []

const data = field.map(item => {
    return {[item]: {mode: 'insensitive', sort: 'desc'}}
})

Output:

[
  { name: { mode: 'insensitive', sort: 'desc' } },
  { address: { mode: 'insensitive', sort: 'desc' } }
]

You can alternatively also use arrow functions to make your code look cleaner, You can learn more about arrow functions here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

const field = ['name', 'address']
const data = field.map(item => ({[item]: {mode: 'insensitive', sort: 'desc'}}));
console.log(data)
  • Related