1

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 + "}"
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. 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 Commented Nov 21, 2017 at 15:14

7 Answers 7

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

enter image description here

EDIT 2 about ptr

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

Sign up to request clarification or add additional context in comments.

11 Comments

Is there a need for the ptr variable?
It's a bad practice to modify a function parameter. At least in the style guide I use airbnb. They say Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the arguments object. It can also cause optimization issues, especially in V8..
I would regard ptr as somewhat academic in this case. In general no-param-reassign is not wrong, but there's little technical reason to obey it here. It would make the code more concise to disregard it here. I don't think the engine optimisations which may or may not happen here make a big difference either way. At least you'd have to benchmark it.
Looks like there is already a discussion on the usefullness: github.com/eslint/eslint/issues/5306
"I would never expect (nor have I ever seen) someone bypass this linter rule (no-param-manipulation) with your second example (reassigning the param variable)" :D
|
2

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);

Comments

2

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);

Comments

1

use reduce.

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


console.log(result);

Comments

1

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).

Comments

0

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)

1 Comment

result[item] = [{type: 'line'}];
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.