Home > Back-end >  How do I get the massaged data form objects using a function
How do I get the massaged data form objects using a function

Time:07-26

I have a object like :

const appUrls = {
  'subject': 'Math',
  'questions': {
    'primary': 12,
    'secondary': 13
   } 
  'marks': '100',
  'students': {
    'primary': 123,
    'secondary': 113
   } 
}

Here, I am trying to get the value from this object using the keys.

I have an array where I have these keys :

    const keys = ["subject","questions","marks", "students"]
  
  keys?.map((code) => {
    const first =  appUrls?.[code]?.['primary']
    const second = appUrls?.[code]?.['secondary']
    const third = appUrls?.[code]
   })   

Here I have to do it like this by creating three different constants. is three any way where I can do it for both the types in one function itself.

CodePudding user response:

I think what you want to achieve can be done by object destructuring

const myObject = { name: "John", surname: "Doe" }
const { name, surname } = myObject
console.log(name, surname) // output: John Doe

More on Object destructuring - MDN Docs

CodePudding user response:

You can do this without using keys array which you are using in your code.

Here is the code:

const appUrls = {
  'subject': 'Math',
  'questions': {
    'primary': 12,
    'secondary': 13
   }, 
  'marks': '100',
  'students': {
    'primary': 123,
    'secondary': 113
   } 
}
  
  for (let x in appUrls) {
  console.log(appUrls[x])
}

And in case you want the value of nested object too then use following code. Without using loop:

const appUrls = {
  'subject': 'Math',
  'questions': {
    'primary': 12,
    'secondary': 13
   }, 
  'marks': '100',
  'students': {
    'primary': 123,
    'secondary': 113
   } 
}
  
  for (let x in appUrls) {
      if(typeof appUrls[x] !== 'object'){
  console.log(appUrls[x])
      }else{
          console.log(appUrls[x]['primary'])
          console.log(appUrls[x]['secondary'])
      }
}

Using loop:

const appUrls = {
  'subject': 'Math',
  'questions': {
    'primary': 12,
    'secondary': 13
   }, 
  'marks': '100',
  'students': {
    'primary': 123,
    'secondary': 113
   } 
}
  
  for (let x in appUrls) {
      if(typeof appUrls[x] !== 'object'){
              console.log(appUrls[x])
      }else{
          for (let y in appUrls[x]) {
              console.log(appUrls[x][y])
          }
      }
}
  • Related