我需要建立以下结构:

 "rows":[
    {//panel1
    },
    {//panel2
    }
    {//panel3 ...
    }
  ]


所以我建立了方法extend,所以我试图这样做,但是它不起作用,因为它只返回最后一个JSON:



var panel_cpu = {"title": "iNeedHelp","smt": 5}

var panel_swap = {"title": "iNeedHelp2","smt":  6}

var combined = $.extend({}, panel_cpu, panel_swap);

//following the comments...

var arr = [];
arr.push(panel_cpu);
arr.push(panel_swap);
////////////////////////////

//following 1 answer
var combined2 = $.extend({}, [panel_cpu, panel_swap]);
//////////////////////////////////////////////////////
var big_panel = {"rows": arr}

console.log(big_panel);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





这里使用的是JQuery,因为我没有找到下划线库

最佳答案

您可以实现如下输出:



var panel_cpu = [{
  "title": "iNeedHelp",
  "smt": 5
}]

var panel_swap = [{
  "title": "iNeedHelp2",
  "smt": 6
}]

var combined = panel_cpu.concat(panel_swap);

var big_panel = [{
  "rows": [combined]
}]

console.log(big_panel);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





但是,您需要具有panel_cpupanel_swqp变量的数组值。发布此文章时,我将提供一个简单的答案。

编辑1

更改此设置将获得如下输出,

var big_panel = {
  "rows": combined
}




var panel_cpu = [{
  "title": "iNeedHelp",
  "smt": 5
}]

var panel_swap = [{
  "title": "iNeedHelp2",
  "smt": 6
}]

var combined = panel_cpu.concat(panel_swap);

var big_panel = {
  "rows": combined
}

console.log(big_panel);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 如何结合两个JSON与扩展并返回它们?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43337299/

10-09 20:53