How to remove nesting of an object?

  • 0
    It is needed from such an array:
    "result": [
        {
            "id": "900",
            "name": "menu",
            "products": {
                "newArray": [
                    {
                        "id": "70",
                        "name": "YO",
                    },
                    {
                        "id": "10",
                        "name": "tEST3",
                    },
                    {
                        "id": "2",
                        "name": "tEST",
                    }
                ]
            }
        },
        {
            "id": "702",
            "name": "menu2",
            "products": {
                "newArray": [
                    {
                        "id": "70",
                        "name": "YO",
                    },
                    {
                        "id": "10",
                        "name": "tEST3",
                    },
                    {
                        "id": "2",
                        "name": "tEST",
                    }
                ]
            }
        }
    ]

    make it like this:
    "result": [
        {
            "id": "900",
            "name": "menu",
            "products": [
                    {
                        "id": "70",
                        "name": "YO",
                    },
                    {
                        "id": "10",
                        "name": "tEST3",
                    },
                    {
                        "id": "2",
                        "name": "tEST",
                    }
                ]
        },
        {
            "id": "702",
            "name": "menu2",
            "products": [
                    {
                        "id": "70",
                        "name": "YO",
                    },
                    {
                        "id": "10",
                        "name": "tEST3",
                    },
                    {
                        "id": "2",
                        "name": "tEST",
                    }
                ]
            }
    ]
    JavaScript Caleb Mayer, May 30, 2019

  • 2 Answers
  • 0
    result.map(({ products: { newArray }, ...item}) => ({ ...item, products: newArray }))


    Or if you are not sure if there is a 'products' property:

    result.map((item) => ({ ...item, products: item?.products?.newArray }))
    Anonymous

  • 0

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!