Home > database >  I want to transform the first Jsonfile into the second Jsonfile with javascript:
I want to transform the first Jsonfile into the second Jsonfile with javascript:

Time:11-19

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

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

And this is the second Json File:

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

I am doing the transformation somehow like this:

            onSubmit: function (errors, values) {
                if (errors) {
                    $('#res').html('<p>Is er iets fout gegaan?</p>');
                } else {
                    const JSONbasis = values.fotos;
                    lengte = JSONbasis.length;
                    for (let i = 0; i < lengte; i  ) {
                        const pValues = Object.values(values.fotos[i]);//values
                        const jsStrVal1 = ('{"foto":'  JSON.stringify(pValues[0]));
                        const jsStrVal2 = JSON.stringify(Object.assign({}, pValues[1]));
                        const result = jsStrVal1.concat(jsStrVal2);
                        const resultB = result.replace('"{"', '","');
                        const resultC = resultB.replaceAll('","', '","zz');
                        resultArray.push([resultC]);
                    }
                    console.log("resultArray= "   resultArray);
                }
            }

But I am sure there is a better way. Any idea?

CodePudding user response:

You could build a new object while iterating the data.

const
    convert = ({ foto: [foto], tekst }) => ({
        foto,
        ...Object.fromEntries(tekst.map((value, index) => [`zz${index}`, value]))
    }),
    data = [{ fotos: [{ foto: ["foto 1"], tekst: ["first line.", "second line.", "third line."] }, { foto: ["foto 2"], tekst: ["first line."] }] }],
    result = data.map(({ fotos }) => ({ fotos: fotos.map(convert) }));

console.log(result);

  • Related