簡體   English   中英

使用JavaScript將數組存儲為JSON中的密鑰對?

[英]Storing array as a key pair in a json using javascript?

一共有三個數組,

var names = ["Increment","Decrement"]
var values1 = [1,2,3,4,5,6] 
var values2 = [7,8,9,10,11]

現在我想構造一個像

{"names":[
    {"Increment":"1,2,3,4,5,6"},
    {"Decrement":"7,8,9,10,11"}
]}

創建一個空對象並更改其屬性。

var names = ["Increment","Decrement"];
var values1 = [1,2,3,4,5,6];
var values2 = [7,8,9,10,11];

var json = [{}];

 json[0].Increment = values1.toString();
 json[0].Decrement = values2.toString();

console.log(JSON.stringify(json));

您可以使用以下方法進行操作:

var names = ["Increment","Decrement"];
var values1 = [1,2,3,4,5,6];
var values2 = [7,8,9,10,11];

var yourArray = [];

for ( var i = 0, len = names.length; i < len; i++ ) {
    o = {};
    o[names[i]] = windows['values'+ i].join(',');
    yourArray.push(o);
}

我建議將數據結構更改為更緊湊的樣式。

var names = ["Increment", "Decrement"],
    values1 = [1, 2, 3, 4, 5, 6],
    values2 = [7, 8, 9, 10, 11],
    obj = {};

obj[names[0]] = values1;
obj[names[1]] = values2;

結果:

{
    Increment: [1, 2, 3, 4, 5, 6],
    Decrement: [7, 8, 9, 10, 11]
}

要生成JSON,您可以使用JSON.stringify()將其轉換為字符串。

\n
\n
\n
var result = {'names' : names.map(function(val, ind) { var elem = {}; elem[val] = this['values' +   ++ind].toString(); return elem; }) };
\n
\n
\n

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM