baDrosa82
baDrosa82

Reputation: 137

How to push object with an array into an array in JS

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

Upvotes: 0

Views: 63

Answers (5)

Mickael Lherminez
Mickael Lherminez

Reputation: 695

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

Upvotes: 0

thiago dias
thiago dias

Reputation: 41

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)

Upvotes: 0

Akshay Bande
Akshay Bande

Reputation: 2587

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

Upvotes: 0

Apak
Apak

Reputation: 177

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

Upvotes: 0

pesho hristov
pesho hristov

Reputation: 2060

Use JSON.stringify ?

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

Upvotes: 1

Related Questions