簡體   English   中英

如何將一堆數組轉換為單個對象?

[英]How to convert a bunch of arrays into a single object?

我在做什么:

onClick,獲取詳細的直接子節點並將其發布在html上。 狀態=完成//效果很好

現在,我正在使用一堆數組來完成此操作。

node.eachSubnode(function(node) {
                   title[title.length] = node.name; // This is what i want to modify
                   data[data.length] = node.data; // This is what i want to modify
                });

它們當前的外觀如下:

title = ['Coffee', 'Tea'];
data = ["Americans", "Britishers"]; // i use a loop to iterate through these arrays and append to html.

這就是我想要的:

var preference = {
title: 'Coffee',
data: 'Americans'
},
{
title: 'Tea',
data: 'Americans
}

我想使用node.eachSubnode循環創建它。

我不確定我是否理解正確,但是我認為這是您想要的:

var preferences = [];

node.eachSubnode(function(node) {
    preferences.push({
        title: node.name,
        data: node.data.germ
    });
});

您不能創建看起來像這樣的對象,我認為您需要一個包含對象的數組。 假設您的節點是具有length屬性的數組,則此方法最快

var preference = new Array(node.length||0), i = 0;
node.eachSubnode(function(node) {
    preference[i++] = {
        title: node.name,
        data: node.data.germ
    };
});

暫無
暫無

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

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