简体   繁体   中英

How to turn array into an nested array of objects and arrays?

I want to combine objects that have the same category number into an array of course s for that category.
But I want the final form to be an array of nested arrays and objects.

I have an array with the following data for example:

var arr = [
    { category : 1, course : "course 1" },
    { category : 1, course : "course 2" },
    { category : 2, course : "course 3" }
]

I want the new array to look like:

output = [
  { category : 1,
    courses : [
      { course : "course 1" },
      { course : "course 2" }
    ]
  },
  { category : 2,
    courses : [
      { course : "course 3" }
    ]
  }
]

Current Code:

var output = [], cnt = 0, i;

for (i = 0; i < arr.length; i++) {
  output[category] = this.coursesData[i];
  cnt++;
}

Current Output:

output = [
    1 : { category : 1, course : "course 2" },
    2 : { category : 2, course : "course 3" },
]

Desired Output:

all the courses with same category need to be merged under that particular category itself.

output = [
  { category : 1,
    courses : [
      { course : "course 1" },
      { course : "course 2" }
    ]
  },
  { category : 2,
    courses : [
      { course : "course 3" }
    ]
  }
]

I have tried merging the array with same id (category in my case) but the desired output is not obtained.

You could try something like this:

const arr = [
    { category: 1, course: "course 1" },
    { category: 1, course: "course 2" },
    { category: 2, course: "course 3" }
];

function transform(arr) {
    const output = {};

    for (let i = 0; i < arr.length; i++) {
        let course = arr[i];
        if (output[course.category]) {
            output[course.category].push(course);
        } else {
            output[course.category] = [];
            output[course.category].push(course);
        }
    }

    const result = [];
    for (let key in output) {
        result.push({
            "category": key,
            "courseList": output[key].map(o => { return { "course": o.course }; })
        })
    }
    console.log(result);
}

transform(arr);

Using Lodash or similar libraries, the logic can be well optimised but for basic understanding, have written code in basic JS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM