-3

Ex:

let jsonArr = { "one", "two", "three" }

Can I modify to make it { "body": [ "one", "two", "three" ], "error": null } using javascript

2 Answers2

2

well, given that there's a typo, and instead of let jsonArr = { "one", "two", "three" } you meant let jsonArr = [ "one", "two", "three" ], sure - why not?

let jsonArr = [ "one", "two", "three" ]
jsonArr = { body: jsonArr, error: null }
Alex Shchur
  • 741
  • 4
  • 13
1

Your question should include the things you have tried.

You just need to build the new object.

e.g.

let jsonArr = [ "one", "two", "three" ]
const jsonObj = Object.assign({}, {
    body: jsonArr,
    error: null,
  });
joshvito
  • 1,498
  • 18
  • 23
  • You missed the curly brackets. And why would you use `Object.assign` for that? – str Jul 17 '20 at 17:37
  • Generally when building a new object from another, this is my habit to prevent unwanted mutations to the original array. In the example above, it is probably overkill since the let is being re-assigned. If you want to keep any existing relations, see @Alexey's answer. – joshvito Jul 17 '20 at 17:47
  • "*Generally when building a new object from another*"–But that is not what you are doing here :) In this case, it is entirely unnecessary. – str Jul 17 '20 at 17:50