[英]Create a string using forEach in javascript
所以我有一個這樣的字符串數組:
myData = ["111", "222", "333"]
我想構建一個具有以下結構的字符串:
"{
"111" : [{"type" : "line"}],
"222" : [{"type" : "line"}],
"333" : [{"type" : "line"}],
}"
基本上,為數組中的每個元素添加該類型和所有行都相同的行,並將其放在花括號中,所有這些都是字符串。
到目前為止,這是我失敗的方法:
let result ="{";
myData.forEach(
result = result + '"' + baselineTitle + '" [{"type":"line"}]';
);
result = result + "}"
我同意@deceze關於使用JSON.stringify
的示例,這是一個示例:
const object = ['111', '222', '333'].reduce((tmp, x) => { tmp[x] = [{ type: 'line', }]; return tmp; }, {}); console.log(JSON.stringify(object, null, 2));
您會注意到Array.reduce的使用是這里最合適的方法。
編輯關於ptr
編輯2關於ptr
最好禁用eslint no-param-ressign規則
您可以先生成對象,然后獲取它的字符串化版本。
var array = ["111", "222", "333"], object = Object.assign(...array.map(k => ({ [k]: [{ type: "line" }] }))), json = JSON.stringify(object); console.log(json); console.log(object);
據我了解,您想在這里獲取JSON。
我將使用JSON.stringify()而不是手動生成它。 我也將使用reduce方法代替forEach
。
const myData = ['111', '222', '333']; const result = JSON.stringify(myData.reduce(function(accumulator, currentValue){ accumulator[currentValue] = [{type: 'line'}]; return accumulator; }, {})); console.log(result);
使用減少 。
const result = ["111", "222", "333"].reduce((prev, curr) => Object.assign(prev, {[curr]: [{type:'line'}]}), {}); console.log(result);
您可以使用reduce將數組轉換成這樣的對象:
const data = ['111', '222', '333']; const result = data.reduce((acc, value) => ( { ...acc, [`${value}`]: [{type: 'line'}] } ), {}); console.log(JSON.stringify(result));
而且我決定在還原情況下使用純無狀態函數編程(無需修改任何范圍變量)。
檢查以下代碼段
const myData = ["111", "222", "333"] const result = {} for( const item of myData) { result[item]=[]; result[item].push({"type" : "line"}); } console.log(result)
forEach循環將一個函數作為參數,您沒有指定參數和函數本身,一個解決方案是這樣的:
let result ="{";
myData.forEach((baselineTitle) => {
result = result + '"' + baselineTitle + '" [{"type":"line"}]';
});
result = result + "}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.