0
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

1

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

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.