Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

How to combine array and an object to a single object? Javascript

I have data in the following format : This is the roww

  [
    {module_id: 152, module_type: "Basics", module_name: "Pre-Reading", duration: 30, 
     course:{"course_name": "Python","course_id": 1}
    },
    {module_id: 153, module_type: "Read", module_name: "Instructional", duration: 40, 
    course:{"course_name": "Python","course_id": 1}
    }
    ]

This is the course

{course_id: 1, course_name: "Python"}

Now how do I convert the data to the following format:

[
  {
        "module": {
            "module_id": 152,
            "module_type": "Basics",
            "module_name": "Pre-Reading",
            "duration": 30,
            "course": {
                "course_name": "Python",
                "course_id": 1
            }
        },
        "course": {
            "course_name": "Python",
            "course_id": 1
        }
    },
    {
        "module": {
            "module_id": 153,
            "module_type": "Read",
            "module_name": "Instructional",
            "duration": 40,
            "course": {
                "course_name": "Python",
                "course_id": 1
            }
        },
        "course": {
            "course_name": "Python",
            "course_id": 1
        }
    }
]

Please help me with this. Thank you in advance :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply use Array.map, Try this

const data = [
  {
    "module_id": 152,
    "module_type": "Basics",
    "module_name": "Pre-Reading",
    "duration": 30,
    "course": {
      "course_name": "Python",
      "course_id": 1
    }
  },
  {
    "module_id": 153,
    "module_type": "Read",
    "module_name": "Instructional",
    "duration": 40,
    "course": {
      "course_name": "Python",
      "course_id": 1
    }
  }
]

const output = data.map(module => ({
  module,
  course: module.course
}))

console.log(output)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...