0

i'm pretty beginner in the JavaScript and I really need help to convert an array to an array object. There are many examples here in stackOverflow, but I need some modidfication during this process, which is why I couldn't do anything

For example I have:

data = [{id: 21, name: "jack"} , {id: 185, name: "yas"}]

and I need to convert it with something like that (id key change to student_id, and present = true, should be added), and the length of this array is dynamic and will change over time.

[
  {
    "student_id" : 21,
    "present" = true
   },
   {
    "student_id" : 185,
    "present" = true
   }  
]

I need to add these array object to:

 const data: any = { 
    here....
  };

your help will be much appreciated.

2
  • 1
    Your example data is not a valid JavaScript data structure. Arrays do not have keys Commented Aug 4, 2021 at 0:31
  • can you check it again Commented Aug 4, 2021 at 0:33

1 Answer 1

1

Assuming your data actually looks more like this

data = [{id: 21, name: "jack"}, {id: 185, name: "yas"}]

This is a simple matter of mapping the array to a new format with the properties you want

const data = [{id: 21, name: "jack"}, {id: 185, name: "yas"}]

const newData = data.map(({ id }) => ({
  student_id: id,
  present: true
}))

console.log(newData)

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

1 Comment

I can't thank you enough, after a tough day, you saved me. Thanks

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.