[英]Create a string using forEach in javascript
So I have an array of strings like this: 所以我有一个这样的字符串数组:
myData = ["111", "222", "333"]
I want to build a string having this structure: 我想构建一个具有以下结构的字符串:
"{
"111" : [{"type" : "line"}],
"222" : [{"type" : "line"}],
"333" : [{"type" : "line"}],
}"
Basically, for each element in array to add that type and line which are the same for all, and put it inside curly brackets, all this being a string. 基本上,为数组中的每个元素添加该类型和所有行都相同的行,并将其放在花括号中,所有这些都是字符串。
This is my unsuccessful approach until now: 到目前为止,这是我失败的方法:
let result ="{";
myData.forEach(
result = result + '"' + baselineTitle + '" [{"type":"line"}]';
);
result = result + "}"
I agree with @deceze about using JSON.stringify
, here is an example : 我同意@deceze关于使用
JSON.stringify
的示例,这是一个示例:
const object = ['111', '222', '333'].reduce((tmp, x) => { tmp[x] = [{ type: 'line', }]; return tmp; }, {}); console.log(JSON.stringify(object, null, 2));
You will notice the use of Array.reduce which is the most adequate method to use in here. 您会注意到Array.reduce的使用是这里最合适的方法。
EDIT about ptr 编辑关于ptr
EDIT 2 about ptr 编辑2关于ptr
It's better to disable the eslint no-param-reassign rule 最好禁用eslint no-param-ressign规则
You could generate the object first and then get a stringified version of it. 您可以先生成对象,然后获取它的字符串化版本。
var array = ["111", "222", "333"], object = Object.assign(...array.map(k => ({ [k]: [{ type: "line" }] }))), json = JSON.stringify(object); console.log(json); console.log(object);
As I understood you want to get JSON here. 据我了解,您想在这里获取JSON。
I would use JSON.stringify() instead of generating it manually. 我将使用JSON.stringify()而不是手动生成它。 Also I would use reduce method instead of
forEach
. 我也将使用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);
You can use reduce to transform an array into an object like this: 您可以使用reduce将数组转换成这样的对象:
const data = ['111', '222', '333']; const result = data.reduce((acc, value) => ( { ...acc, [`${value}`]: [{type: 'line'}] } ), {}); console.log(JSON.stringify(result));
And I decided to use pure stateless functional programming for the reduce case (without modifying any scope variable). 而且我决定在还原情况下使用纯无状态函数编程(无需修改任何范围变量)。
Check the following snippet 检查以下代码段
const myData = ["111", "222", "333"] const result = {} for( const item of myData) { result[item]=[]; result[item].push({"type" : "line"}); } console.log(result)
The forEach loop takes a function as argument, you did not specify arguments and the function itself, a solution would be like this : forEach循环将一个函数作为参数,您没有指定参数和函数本身,一个解决方案是这样的:
let result ="{";
myData.forEach((baselineTitle) => {
result = result + '"' + baselineTitle + '" [{"type":"line"}]';
});
result = result + "}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.