简体   繁体   中英

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 :

 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.


EDIT about ptr

在此处输入图片说明

EDIT 2 about ptr

It's better to disable the eslint no-param-reassign rule

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.

I would use JSON.stringify() instead of generating it manually. Also I would use reduce method instead of forEach .

 const myData = ['111', '222', '333']; const result = JSON.stringify(myData.reduce(function(accumulator, currentValue){ accumulator[currentValue] = [{type: 'line'}]; return accumulator; }, {})); console.log(result); 

use reduce .

 const result = ["111", "222", "333"].reduce((prev, curr) => Object.assign(prev, {[curr]: [{type:'line'}]}), {}); console.log(result); 

You can use reduce to transform an array into an object like this:

 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 :

let result ="{";
myData.forEach((baselineTitle) => {
    result = result + '"' + baselineTitle + '" [{"type":"line"}]'; 
});
result = result + "}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM