1

I have array like this .

const test = [
    { student: { id : '1', Name: 'A' }, marks: {
 id: '2', Name: 'B'
} }, 
    { student: {
 id : '3', Name: 'C' }, marks: { id: '4', Name: 'D' } }
]

Now, from this array of object , I am trying to create two diff arrays which will be having seperate student and marks keys .

const student = [{"student":{"Id": {value: "A"}}}, {"student":{"Id": {value: "B"}}}]

and for marks

const marks = [{"marks":{"Id": {value: "C"}}}, {"marks":{"Id": {value: "D"}}}]

SO, Here what I tried is

test.map((index,item) => {
    return [item.student] 
  })

can any one help me with this ?

Thanks.

1
  • In general, this is "bad practice" (Especially when you working with databases like MongoDB) to start changing the data structure and nesting + property names (id to Id) without a lot of meaning -or- semantic. In your case before change console.log(test[0].student.id) (return 1). After console.log(student[0].student.Id.value) (Return A and not 1). Commented Sep 4, 2020 at 5:40

1 Answer 1

4

You want a new object returned, not a sub array.

Following uses destructuring to simplify the returned object

const test = [
    { student: { id : '1', Name: 'A' }, marks: {
id: '2', Name: 'B'
} }, 
    { student: {
id : '3', Name: 'C' }, marks: { id: '4', Name: 'D' } }
]

const students = test.map(({student}) => ({student}))
const marks = test.map(({marks}) => ({marks}))

console.log(students)
console.log(marks)

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

9 Comments

yes this one will work but I have to add new property as well, in this which will be value rather than id, and Name.
and also How do I return both of the new objects from the same map function.
just to make my nswer simple in a comment, use another map(). Or create the two arrays nd then use forEach() and push each object to associated array
As for other properties ...map(({student}) => ({student, someProperty: someValue}));
So, this will remove the existing values and add the new property right
|

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.