我有以下代碼:
const sample = [
{
name: "apple",
points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
age: 24
},
{
name: "banana",
points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
age: 45
}
];
const qwer = JSON.stringify(sample, null, 2);
console.log(qwer);
如果你運行它,你會注意到它有很好的格式,除了點陣列,它非常冗長。
我希望所有內容都像往常一樣縮進(這就是為什么我將 2 作為最后一個引數傳遞給 stringify 的原因),但我希望 points 陣列只占用一行,就像它在代碼中宣告的方式一樣。
這樣做的原因是因為目前每個點陣列都被拉伸到 18 行,而當時只有 3 或 4 個專案。我希望他們保持在一條線上。
我嘗試使用自定義替換器,雖然它有點作業,但它強制 JSON 陣列成為一個字串。但它不是一個字串。我希望它保持一個陣列。
有沒有辦法做到這一點?
uj5u.com熱心網友回復:
對于一般的解決方案,迷你決議器將是最好的方法,但一種快速但難看的方法是使用替換器將陣列替換為具有唯一值作為前綴的字串化字串,然后可以替換。
const sample = [
{
name: "apple",
age: 24,
points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
},
{
name: "banana",
age: 45,
points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
}
];
const withNestedStringifiedArrays = JSON.stringify(
sample,
(key, value) => key && Array.isArray(value) ? '@@UNIQUE@@' JSON.stringify(value) : value,
2
);
const output = withNestedStringifiedArrays.replace(
/"@@UNIQUE@@(.*?)"(,)?$/gm,
(_, stringifiedArr, possibleComma = '') => stringifiedArr.replaceAll('\\', '') possibleComma
);
console.log(output);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/462169.html
標籤:javascript json 细绳 格式化 字符串化
上一篇:如何過濾兩個陣列?
