Search code examples
javascriptarraysjsonarray-merge

I want to merge values of a nested Json object with javascript:


So How to merge values of a Json object like this: {"zz0": "value 1","zz1": "value 2","zz2": "value 3"} into this: {"key":["value 1","value 2","value 3"]} In my javascript form this is the first Json file:

    [
        {
            "fotos": [
                {
                    "foto": "foto 1",
                    "zz0": "first line.",
                    "zz1": "second line.",
                    "zz2": "third line."
                },
                {
                    "foto": "foto 2",
                    "zz0": "first line."
                }
            ]
        }
    ]

And this is the second Json File:

    [
        {
            "fotos": [
                {
                    "foto": ["foto 1"],
                    "tekst": ["first line.", "second line.", "third line."]
                },
                {
                    "foto": ["foto 2"],
                    "tekst": ["first line."]
                }
            ]
        }
    ]

Searched a solution with map and arrow functions but got stuck... Any idea?


Solution

  • const arr = [{ "fotos": [{ "foto": "foto 1", "zz0": "first line.", "zz1": "second line.", "zz2": "third line." }, { "foto": "foto 2", "zz0": "first line." }]}];
    
    const ans = arr.map(({fotos}) => ({fotos: fotos.map(({foto, ...res}) =>({foto: [foto], tekst: Object.values(res)}))}));
    
    console.log(ans);