我想用javascript将第一个Jsonfile转换为第二个Jsonfile:

2wnc66cl  于 2022-11-19  发布在  Java
关注(0)|答案(1)|浏览(127)

如何像这样拆分Json对象的值:{“键”:[“值1”,“值2”,“值3”]}转换为:{“zz 0”:“值1”,“zz 1”:“值2”、“zz 2”:“value 3”}在我的javascript表单中,这是第一个Json文件:

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

这是第二个Json文件:

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

我在做这样的转换:

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);
                }
            }

但我相信有更好的办法。你有什么想法吗?

3bygqnnd

3bygqnnd1#

您可以在迭代数据的同时构建新对象。

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);

相关问题