Mr. Learner
Mr. Learner

Reputation: 1038

combine two array of object from same response - JS

What is the best way to combine two array of object from same response?

let data = [{
   "testLevel":"mid",
   "testId":"m-001",
   "majorCourse": [
      {
         "courseName":"C++",
      }
   ],
   "additinalCertificate" : [
      {
         "courseName":"Data Structure",
      }
      {
         "courseName":"Intra Networking and design - level 1",
      }
   ]
}]

expected:

newObj = [{{"courseName":"C++"},{"courseName":"DS"}}]

Here what i'm trying to achieve is. i want to bind data in my angular app *(not using nested 'ngFor' for some reason) like

1. C++
2. C++ + DS

so tired

let combine = [...data[0].majorCourse, ...data[0].additinalCertificate];

console.log('combine',combine); // getting undefined

could someone tell me how to achieve this with es6 or better solution?

Thanks

Upvotes: 0

Views: 57

Answers (1)

SMAKSS
SMAKSS

Reputation: 10520

First of all, keep in mind there is no property with the value of java in your actual data object. Then you missed a comma (',') in your data, additinalCertificate property and last of all, to access the "courseName":"Data Structure" in additinalCertificate you need to mention its index. Also, the last part with the index of courseName will not be iterable so there is no need to use spread syntax on it.

Your final code should be something like this:

let data = [{
  "testLevel": "mid",
  "testId": "m-001",
  "majorCourse": [{
    "courseName": "C++",
  }],
  "additinalCertificate": [{
    "courseName": "Data Structure",
  }, {
    "courseName": "Intra Networking and design - level 1",
  }]
}]

let combine = [...data[0].majorCourse, data[0].additinalCertificate[0]];

console.log('combine: ', combine)

Upvotes: 1

Related Questions