0

See jobs in the log? It's not an array, how to push it as an array (so I can access it via loop).

https://jsfiddle.net/1jo43e8c/1/

var name = "John"
var age = 30
var jobs = ['a', 'b', 'c']

obj = []

obj.push('{name: "'+name+'", age: "'+age+'", jobs: '+jobs+'}')

console.log(obj) // result: ["{name: "John", age: "30", jobs: a,b,c}"]    
/////////////////// goal: ["{name: "John", age: "30", jobs: ["a","b","c"]}"]
6
  • 3
    Not sure what you're after, but using JSON.stringify() instead of your custom serialization might help. Commented Dec 12, 2019 at 11:58
  • Why are you building JSON manually? If you want to push a JSON string, why not prepare it as a proper object then push it via JSON.stringify()? Commented Dec 12, 2019 at 11:58
  • 3
    obj.push(JSON.stringify({name, age, jobs})) should do what you need Commented Dec 12, 2019 at 11:59
  • I do not understand your question, you want to push an object in a table is that? Commented Dec 12, 2019 at 12:00
  • 1
    jobs: '+jobs+' this calls toString() method on array. As @VladimirBogomolov mentioned you don't need string concatenation to create an object Commented Dec 12, 2019 at 12:00

5 Answers 5

1

Use JSON.stringify ?

obj.push('{name: "'+name+'", age: "'+age+'", jobs: '+ JSON.stringify(jobs)+'}')
Sign up to request clarification or add additional context in comments.

Comments

0

I think what you are trying to do is

obj.push({jobs:['a', 'b', 'c'], age:30, name:'John'})

Also take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Comments

0

Use map on array.

var name = "John"
var age = 30
var jobs = ['a', 'b', 'c']
obj = [];
let temp = jobs.map((v) => `"${v}"`);
obj.push(`{name: ${name}, age: ${age}, jobs: [${temp.join(",")}]}`)
console.log(obj) // ["{name: "John", age: "30", jobs: a,b,c}"]

Comments

0

One solution is map the array and then change the value of each item before push into obj.

var name = "John"
var age = 30
var jobs = ['a', 'b', 'c']
jobs = jobs.map(item => `"${item}"` );

obj = []

obj.push('{name: "'+name+'", age: "'+age+'", jobs: ['+jobs+']}')


console.log(obj)

Comments

0

This gives what you want.

var name = "John"
var age = 30
var jobs = ['a', 'b', 'c']

var obj = []

obj.push(`{name: '${name}', age: '${age}', jobs: [${JSON.stringify(jobs)}}]`)



console.log(obj)   
// goal: ["{name: "John", age: "30", jobs: [a,b,c]}"]

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.