最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Create a string using forEach in javascript - Stack Overflow

programmeradmin4浏览0评论

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 + "}"

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 + "}"
Share Improve this question asked Nov 21, 2017 at 15:11 Samurai JackSamurai Jack 3,1359 gold badges36 silver badges59 bronze badges 2
  • 4 Do you happen to want to create a JSON string…? Then create an object according to your desired format and JSON.stringify it. – deceze Commented Nov 21, 2017 at 15:13
  • 3 Never create json manually. It is error prone and more work than creating objects/arrays and serializing them – charlietfl Commented Nov 21, 2017 at 15:14
Add a ment  | 

7 Answers 7

Reset to default 3

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 + "}"
发布评论

评论列表(0)

  1. 暂无评论