如何将带有数组的对象推入JS中的数组

时间:2019-12-12 11:56:19

标签: javascript

在日志中看到jobs吗?它不是数组,如何将其作为数组推送(这样我就可以通过循环访问它了。)

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

5 个答案:

答案 0 :(得分:1)

使用JSON.stringify吗?

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

答案 1 :(得分:0)

我认为您想做的是

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

还可以看看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

答案 2 :(得分:0)

在数组上使用映射。

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

答案 3 :(得分:0)

一种解决方案是映射数组,然后在推入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)

答案 4 :(得分:0)

这给出了您想要的。

O(n^2)