那么如何像這樣拆分 Json 物件的值:{"key":["value 1","value 2","value 3"]} 成這樣:{"zz0": "value 1","zz1" : "value 2","zz2": "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);
}
}
但我相信有更好的方法。任何想法?
uj5u.com熱心網友回復:
您可以在迭代資料時構建一個新物件。
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/537044.html
上一篇:PHP。如何在表格從HTML中消失后獲取$_POST值
下一篇:在Django中保存外鍵
