Search code examples
javascriptarraysarrayobject

transform array of object into new array following with its child


i have an array like this

var data = [
    {
        name: "Movies", info: "category_name",
        content: [
            { name: "Interstellar", info: "category_data" },
            { name: "Dark Knight", info: "category_data" },
        ]
    },
    {
        name: "Music", info: "category_name",
        content: [
            { name: "Adams", info: "category_data" },
            { name: "Nirvana", info: "category_data" },
        ]
    },
    {
        name: "Places", info: "category_name",
        content: [
            { name: "Jordan", info: "category_data" },
            { name: "Punjab", info: "category_data" },
        ]
    },
]

and a want to transform it into like this

var transformedArray= [
  { name: "Movies", info: "category_name" },
  { name: "Interstellar", info: "category_data" },
  { name: "Dark Knight", info: "category_data" },
  { name: "Music", info: "category_name" },
  { name: "Adams", info: "category_data" },
  { name: "Nirvana", info: "category_data" },
  { name: "Places", info: "category_name" },
  { name: "Jordan", info: "category_data" },
  { name: "Punjab", info: "category_data" },
]

i dont know what is the keyword suitable for this case , i have tried mapping it into new array but it's not same like i expected

var newArr = []

var manipulate = data.map(item => {
    return (
        newArr.push(item),
        new1.map(items => {
            return (
                new1.push(items)
            )
        })
    )
})

then how to manipulate "data" into "transformedArray"


Solution

  • Use Array.prototype.flatMap(). If your browser or version of Node.js does not yet natively support this function, you can include a simple polyfill below, based on the specification:

    if (!Array.prototype.flatMap) {
      Object.defineProperty(Array.prototype, 'flatMap', {
        configurable: true,
        writable: true,
        value: function flatMap (callback, thisArg = undefined) {
          return this.reduce((array, ...args) => {
            const element = callback.apply(thisArg, args);
    
            if (Array.isArray(element)) array.push(...element);
            else array.push(element);
    
            return array;
          }, []);
        }
      });
    }
    
    const data = [{name:'Movies',info:'category_name',content:[{name:'Interstellar',info:'category_data'},{name:'Dark Knight',info:'category_data'}]},{name:'Music',info:'category_name',content:[{name:'Adams',info:'category_data'},{name:'Nirvana',info:'category_data'}]},{name:'Places',info:'category_name',content:[{name:'Jordan',info:'category_data'},{name:'Punjab',info:'category_data'}]}];
    const transformedArray = data.flatMap(({ content, ...o }) => [o, ...content]);
    
    console.log(transformedArray);